Wardon&ET 博客

PHPExcel读取图片

参考资料 https://www.cnblogs.com/itbsl/p/11883458.html

参考资料里面用imagecreatefrompng生成图片容易内存溢出,我改进了一下,直接复制图片

<?
require_once(COMMON_CONFIG_PATH.'/core/plugin/PHPExcel/IOFactory.php');
require_once(COMMON_CONFIG_PATH.'/core/plugin/PHPExcel/Cell.php');
try {
    $inputFileName = 'tu.xlsx';
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($inputFileName);
} catch (\Exception $e) {
    die('加载文件发生错误:"'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$sheet = $objPHPExcel->getSheet(0);
$data = $sheet->toArray();
$imageFilePath = 'img/'; //图片本地存储的路径
if (!file_exists($imageFilePath)) {
    mkdir($imageFilePath, 0777, true);
}

//处理图片
foreach ($sheet->getDrawingCollection() as $img) {
    list($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($img->getCoordinates()); //获取图片所在行和列
    $imageFileName = $img->getCoordinates() . mt_rand(1000, 9999);
    $ext = $img->getExtension()!='jpg'?:'jpeg';
    $imageFileName .= $ext;
    copy($img->getPath(),$imageFilePath.$imageFileName);

    $startColumn = ABC2decimal($startColumn);
    $data[$startRow-1][$startColumn] = $imageFilePath . $imageFileName;

}
print_r($data);

function ABC2decimal($abc)
{
    $ten = 0;
    $len = strlen($abc);
    for($i=1;$i<=$len;$i++){
        $char = substr($abc,0-$i,1);//反向获取单个字符

        $int = ord($char);
        $ten += ($int-65)*pow(26,$i-1);
    }
    return $ten;
}