Categories : PHP

You can change XLS to XLSX, CSV or any type or excel that PhpSpreadsheet supports after that you can download all images in excel file.

<?php

require 'vendor/autoload.php';


# save images from "E" column of file with phpspreadsheed library

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();

$spreadsheet = $reader->load(__DIR__ . '/data.xls');

use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
$i = 0;

foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) {
    if ($drawing instanceof MemoryDrawing) {
        ob_start();
        call_user_func(
            $drawing->getRenderingFunction(),
            $drawing->getImageResource()
        );
        $imageContents = ob_get_contents();
        ob_end_clean();
        switch ($drawing->getMimeType()) {
            case MemoryDrawing::MIMETYPE_PNG :
                $extension = 'png';
                break;
            case MemoryDrawing::MIMETYPE_GIF:
                $extension = 'gif';
                break;
            case MemoryDrawing::MIMETYPE_JPEG :
                $extension = 'jpg';
                break;
        }
    } else {
        if ($drawing->getPath()) {
            // Check if the source is a URL or a file path
            if ($drawing->getIsURL()) {
                $imageContents = file_get_contents($drawing->getPath());
                $filePath = tempnam(sys_get_temp_dir(), 'Drawing');
                file_put_contents($filePath , $imageContents);
                $mimeType = mime_content_type($filePath);
                // You could use the below to find the extension from mime type.
                // https://gist.github.com/alexcorvi/df8faecb59e86bee93411f6a7967df2c#gistcomment-2722664
                $extension = File::mime2ext($mimeType);
                unlink($filePath);
            }
            else {
                $zipReader = fopen($drawing->getPath(),'r');
                $imageContents = '';
                while (!feof($zipReader)) {
                    $imageContents .= fread($zipReader,1024);
                }
                fclose($zipReader);
                $extension = $drawing->getExtension();
            }
        }
    }
    $myFileName = '00_Image_'.++$i.'.'.$extension;
    file_put_contents($myFileName,$imageContents);
}

Leave a Reply

Your email address will not be published. Required fields are marked *