PHPExcel读取图片并保存
今天在项目开发时,突然遇到了一个问题,就是一个Excel需要保存文字和图片,把文字和图片分别存入数据库,然后就Google了一下
搜到以下文章
1 https://www.shenyao.net/show-5-6474.html 报错 $drawing->getRenderingFunction()和 $drawing->getImageResource()不存在,因为这两个方法是PHPExcel_Worksheet_MemoryDrawing对象的, $drawing是PHPExcel_Worksheet_Drawing对象
2 https://blog.51cto.com/php2012web/1620057 报错 $img->getImageResource()不存在,原因和上一条一样
3 http://www.07net01.com/2017/03/1833348.html $drawing->getDescription() 返回值 为空.所以要做些修改才可以
上面1和2得使用Excel5才可以
4 又发现一篇博客的方法可行而且很简单,https://blog.csdn.net/evkj2013/article/details/65441170 第49行开始就是操作Excel2007. $drawing->getIndexedFilename()直接得到的是文件名
3的代码做如下修改就可以了
$filename = $drawing->getPath();
$img = 'upload/excel_img/' . uniqid() . ".jpg";// 扩展名在实际情况下不应该写死
copy($filename, $img);
$cell = $sheet->getCell($string);
$cell->setValue($img);
我们的PHPExcel版本是1.7.9
后来看源码,发现如下代码
Excel2007.php
第311行
if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) {
$imageContents = null;
$imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
if (strpos($imagePath, 'zip://') !== false) {
$imagePath = substr($imagePath, 6);
$imagePathSplitted = explode('#', $imagePath);
$imageZip = new ZipArchive();
$imageZip->open($imagePathSplitted[0]);
$imageContents = $imageZip->getFromName($imagePathSplitted[1]);
$imageZip->close();
unset($imageZip);
}
最外面的if里的对象就是第三篇文章$drawing的对象,那么我们可以根据这部分源来做些修改
foreach ($sheet->getDrawingCollection() as $drawing) {
$string = $drawing->getCoordinates();
if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
$imagePath = $drawing->getPath();
$imagePath = substr($imagePath, 6);
$imagePathSplitted = explode('#', $imagePath);
$imageZip = new ZipArchive();
$imageZip->open($imagePathSplitted[0]);
$imageContents = $imageZip->getFromName($imagePathSplitted[1]); // 这里得到图片的数据流
$imageZip->close();
unset($imageZip);
$expanded = '.' . explode('.', $imagePathSplitted[1])[1]; // 获取扩展名
$img = "/upload/excel_img/" . uniqid() . mt_rand(10000, 99999) . $expanded;
file_put_contents("." . $img, $imageContents);
$cell = $sheet->getCell($string);
$cell->setValue($img);
}
这样修改就ok了
其中 $imagePath 值是这样的 “zip:///data/www/xxx/bdac99339.xlsx#xl/media/image2.jpg”
上一篇: MyCat 简介
下一篇: php实现基本的日历显示与实时查询功能