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;
}
正如
布拉德上面所说,没有必要使用 GD 库,也不需要写入文件或其他任何东西。只需回显 zip_entry_read() 函数的结果并设置内容类型。你可以使用这样的东西:
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));
if ($theimg !== null) {
header('Content-Type: image/jpeg');
echo $theimg;
}
else { echo "Could not load image."; }
zip_entry_close($zip_entry);
}
}
else { echo "Could not open."; }
}
zip_close($zip);
}
else { echo "File not found."; }
}
我认为只是不加载GD库应该可以很好地提高性能。