加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

使用PHP从ZIP存档中查找和显示图像文件的最简单方法

发布时间:2020-12-13 17:41:15 所属栏目:PHP教程 来源:网络整理
导读:function showimage($zip_file,$file_name) { if (file_exists($zip_file)) { $zip = zip_open($zip_file); while ($zip_entry = zip_read($zip)) { if (zip_entry_open($zip,$zip_entry,"r")) { if (zip_entry_name($zip_entry) == $file_name) { $theimg =
function showimage($zip_file,$file_name) {
    if (file_exists($zip_file)) {
        $zip = zip_open($zip_file);
        while ($zip_entry = zip_read($zip)) {
            if (zip_entry_open($zip,$zip_entry,"r")) {
                if (zip_entry_name($zip_entry) == $file_name) {
                    $theimg = zip_entry_read($zip_entry,zip_entry_filesize($zip_entry));
                    $theimg = imagecreatefromstring($theimg);
                    if ($theimg !== false) {
                        header('Content-Type: image/jpeg');
                        imagejpeg($theimg);
                        imagedestroy($theimg);
                    }
                    else { echo "Could not create image."; }
                    zip_entry_close($zip_entry);
                }
            }
            else { echo "Could not open."; }
        }
        zip_close($zip);
    }
    else { echo "File not found."; }
}

我正在运行此函数来打开指定的zip文件,然后循环遍历内容以查找指定的文件名,然后从该文件创建图像而无需提取.我有点好奇这个过程是如何系统密集的,如果有一个更整洁/更直接的方式在zip存档中查找文件而不需要循环查看名称是否与给定的文件名匹配.无论如何直接从具有给定名称的zip文件调用文件,假设它存在?

上面的代码有效……我想我只是想看看如何做得更好.如果这是有道理的.

解决方法

ZipArchive有一种获取文件而无需实际搜索的方法.

function showimage($zip_file,$file_name) {
    $z = new ZipArchive();
    if ($z->open($zip_file) !== true) {
        echo "File not found.";
        return false;
    }

    $stat = $z->statName($file_name);
    $fp   = $z->getStream($file_name);
    if(!$fp) {
        echo "Could not load image.";
        return false;
    }

    header('Content-Type: image/jpeg');
    header('Content-Length: ' . $stat['size']);
    fpassthru($fp);
    return true;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读