PHP Zip压缩导出图片,直接下载图片

PHP Zip压缩导出图片,直接下载图片

1.需求,根据url导出图片

2.思路

  准备好图片地址,想要保存的文件名称,在一个数组中

  启动打开zip文件

  下载文件添加到zip中

  下载zip到本地

3.实现代码

第一种zip压缩导出图片,耗时较长,实现简单,

<?php
    // 开始时间
    $stime=microtime(true);
    // 数据
    $data="'Test04255','Test04254','Test04253','Test04252','Test04251','Test04250'";
    //$data=file_get_contents(dirname(__FILE__).'/kuhao.txt');
    //连接数据库
    $pdo = new PDO("mysql:host=127.0.0.1;dbname=dbname","root","root");
    $sql="SELECT `image`,`library_number`,`carousel_image`,`detail` FROM `art_info` WHERE `library_number` IN ({$data})";
    $cx=$pdo ->query($sql,$pdo::FETCH_ASSOC);
    $list=$cx->fetchAll($pdo::FETCH_ASSOC);
    //文件路径
    $tmpDir = $_SERVER['DOCUMENT_ROOT'].'\\'.'downimg\\';
    if (!file_exists($tmpDir)) {
        //创建文件夹
        mkdir($tmpDir, 0777, true);
    }
    // 定义文件信息
    $zipName='tupian.zip';
    // 实例化zip类
    $zip = new \ZipArchive();
    $zipNameUrl = $tmpDir . $zipName;
    if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
        //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
        if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
            // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
            return  '下载失败,文件夹不存在';
        }
    }
    // 循环保存图片信息
    foreach ($list as $lis){
        // 第一个默认的图
        $picAllArr[] = ['fileurl'=>$lis['image'],'filename'=>$tmpDir.$lis['library_number'].'\image.'.pathinfo($lis['image'])['extension'],'dirname'=>$lis['library_number']];
        $zip->addEmptyDir($lis['library_number']);
        // 多图
        $lis['carousel_image_arr'] = array_filter(explode(',', $lis['carousel_image']));
        foreach ($lis['carousel_image_arr'] as $key => $imagear){
            $ext = pathinfo($imagear)['extension'];
            $picAllArr[] = ['fileurl'=>$imagear,'filename'=>$tmpDir.$lis['library_number'].'\carousel_image'.++$key.'.'.$ext,'dirname'=>$lis['library_number']];
        }
        // 详情图
        $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern,$lis['detail'],$match);
        foreach ($match[1] as $key => $v){
            $ext = pathinfo($v)['extension'];
            $picAllArr[] = ['fileurl'=>$v,'filename'=>$tmpDir.$lis['library_number'].'\detail'.++$key.'.'.$ext,'dirname'=>$lis['library_number']];
        }
    }
    // 开始时间
    $yasuotusttime=microtime(true);
    foreach ($picAllArr as $file) {
        //判断图片是否存在
        $isFile = checkFileExists($file['fileurl']);
        if (!$isFile) {
            continue;
        }
        //抓取图片内容
        $fileContent = file_get_contents($file['fileurl']);
        //添加图片到zip中
        $zip->addFromString($file['dirname'].'\\'.basename($file['filename']), $fileContent);
    }
    // 结束时间
    $yasuotuendtime=microtime(true);
    $zip->close();

    $etime=microtime(true);

    $xiazaitime=$yasuotuendtime-$yasuotusttime;
    $toime=$etime-$stime;
    echo "当前页面执行时间为:{$toime}秒,下载时间{$xiazaitime}秒";
    exit;
// 判断文件是哪里的,是否存在
function checkFileExists($file){
    // 远程文件
    if (strtolower(substr($file, 0, 5)) == 'https') {
        // 远程文件
        $header = get_headers($file, true);
        return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));

    } elseif (strtolower(substr($file, 0, 4)) == 'http') {
        // 远程文件
        $header = get_headers($file, true);
        return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
    } else {
        // 本地文件
        return file_exists($file);
    }
}
?>

第二种,耗时较短,使用缓存

//文件路径
    $tmpDir = $_SERVER['DOCUMENT_ROOT'].'/'.'downimg/';
    if (!file_exists($tmpDir)) {
        //创建文件夹
        mkdir($tmpDir, 0777, true);
    }

    // 循环保存图片信息
    foreach ($list as $lis){

        // 第一个默认的图
        $picAllArr[] = ['fileurl'=>$lis['image'],'filename'=>$tmpDir.$lis['library_number'].'/image.'.pathinfo($lis['image'])['extension'],'dirname'=>$lis['library_number']];
        //$zip->addEmptyDir($lis['library_number']);
        if (!file_exists($tmpDir.$lis['library_number'])){
            mkdir ($tmpDir.$lis['library_number'],0777,true);
        }
        // 多图
        $lis['carousel_image_arr'] = array_filter(explode(',', $lis['carousel_image']));
        foreach ($lis['carousel_image_arr'] as $key => $imagear){
            $ext = pathinfo($imagear)['extension'];
            $picAllArr[] = ['fileurl'=>$imagear,'filename'=>$tmpDir.$lis['library_number'].'/carousel_image'.++$key.'.'.$ext,'dirname'=>$lis['library_number']];
        }
        // 详情图
        $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern,$lis['detail'],$match);
        foreach ($match[1] as $key => $v){
            $ext = pathinfo($v)['extension'];
            $picAllArr[] = ['fileurl'=>$v,'filename'=>$tmpDir.$lis['library_number'].'/detail'.++$key.'.'.$ext,'dirname'=>$lis['library_number']];
        }
    }
    // 开始时间
    $yasuotusttime=microtime(true);
    foreach ($picAllArr as $file) {
        //判断图片是否存在
        $isFile = checkFileExists($file['fileurl']);
        if (!$isFile) {
            continue;
        }
        // 开启输出缓存区
        ob_start();
        readfile($file['fileurl']);
        $img = ob_get_contents();
        ob_end_clean();
        //抓取图片内容
        $myfile=fopen($file['filename'],'a');
        fwrite($myfile,$img);
        fclose($myfile);
        //添加图片到zip中
    }
    // 结束时间
    $yasuotuendtime=microtime(true);
    $etime=microtime(true);
    $xiazaitime=$yasuotuendtime-$yasuotusttime;
    $toime=$etime-$stime;
    echo "当前页面执行时间为:{$toime}秒,下载时间{$xiazaitime}秒";
    exit;
// 判断文件是哪里的,是否存在
function checkFileExists($file){
    // 远程文件
    if (strtolower(substr($file, 0, 5)) == 'https') {
        // 远程文件
        $header = get_headers($file, true);
        return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));

    } elseif (strtolower(substr($file, 0, 4)) == 'http') {
        // 远程文件
        $header = get_headers($file, true);
        return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
    } else {
        // 本地文件
        return file_exists($file);
    }
}

第三种,推荐,简洁方便

    //文件路径
    $tmpDir = './downimg/';
    if (!file_exists($tmpDir)) {
        //创建文件夹
        mkdir($tmpDir, 0777, true);
    }


    // 开始时间
    $yasuotusttime=microtime(true);
    $imgcount=0;
    // 循环保存图片信息
    foreach ($list as $lis){
        if (!file_exists($tmpDir.$lis['library_number'])){
            mkdir ($tmpDir.$lis['library_number'],0777,true);
        }

        downimg($lis['image'],$tmpDir.$lis['library_number'].'/image.'.pathinfo($lis['image'])['extension'],$imgcount);
        // 第一个默认的图
        // 多图
        $lis['carousel_image_arr'] = array_filter(explode(',', $lis['carousel_image']));
        foreach ($lis['carousel_image_arr'] as $key => $imagear){
            $ext = pathinfo($imagear)['extension'];
            downimg($imagear,$tmpDir.$lis['library_number'].'/carousel_image'.++$key.'.'.$ext,$imgcount);
        }
        // 详情图
        $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern,$lis['detail'],$match);
        foreach ($match[1] as $key => $v){
            $ext = pathinfo($v)['extension'];
            downimg($v,$tmpDir.$lis['library_number'].'/detail'.++$key.'.'.$ext,$imgcount);
        }
    }

    // 下载文件
    function downimg($fileurl,$filename,&$imgcount){

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$fileurl);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $data = curl_exec($ch);
        $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);
        if($code!=200){
            return;
        }
        $file = fopen($filename,"a");
        fwrite($file,$data); //写入文件
        fclose($file);
        $imgcount++;
    }
    // 结束时间
    $yasuotuendtime=microtime(true);
    $etime=microtime(true);
    $xiazaitime=$yasuotuendtime-$yasuotusttime;
    $toime=$etime-$stime;
    echo "当前页面执行时间为:{$toime}秒,下载时间{$xiazaitime}秒,共{$imgcount}张图";
    exit;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值