gpt4 book ai didi

php - 使用 PHP 从 ZIP 存档中查找和显示图像文件的更简洁的方法

转载 作者:可可西里 更新时间:2023-10-31 22:14:14 26 4
gpt4 key购买 nike

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;
}

关于php - 使用 PHP 从 ZIP 存档中查找和显示图像文件的更简洁的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10179435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com