如何使用 PHP 压缩图像文件并提取它?我的代码产生损坏的提取
我有一个表单,用户可以在其中上传 100 MB 文件,这会导致上传延迟,因此我决定首先在表单提交上压缩图像,然后将其上传到服务器上,然后将其提取到服务器上。这样加载过程就会减少,因此为此我使用了如下脚本:
<?php
$zip = new ZipArchive();
$filename = "newzip.zip";
if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString("myfile.jpeg",
"This is the first file in our ZIP, added as
firstfile.txt.\n");
echo "numfiles: " . $zip->numFiles . "\n";
$zip->close();
$zip1 = zip_open("newzip.zip");
if ($zip1) {
while ($zip_entry = zip_read($zip1)) {
$fp = fopen(zip_entry_name($zip_entry), "w");
if (zip_entry_open($zip1, $zip_entry, "r")) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
fwrite($fp,"$buf");
zip_entry_close($zip_entry);
fclose($fp);
}
}
zip_close($zip1);
unlink("newzip.zip");
}
?>
现在从上面的代码中我提取了图像,但提取后图像的大小减少到 61 字节并且已损坏,即它不能被已查看。
这段代码可能有什么问题,请指导我
i have a form in which user can upload 100 mb file which results delay in upload, hence I decided to first zip the image on form submit and then upload it on server and then extract it on server. so that loading process decreases, Hence for this I have used a script which is as follows:
<?php
$zip = new ZipArchive();
$filename = "newzip.zip";
if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString("myfile.jpeg",
"This is the first file in our ZIP, added as
firstfile.txt.\n");
echo "numfiles: " . $zip->numFiles . "\n";
$zip->close();
$zip1 = zip_open("newzip.zip");
if ($zip1) {
while ($zip_entry = zip_read($zip1)) {
$fp = fopen(zip_entry_name($zip_entry), "w");
if (zip_entry_open($zip1, $zip_entry, "r")) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
fwrite($fp,"$buf");
zip_entry_close($zip_entry);
fclose($fp);
}
}
zip_close($zip1);
unlink("newzip.zip");
}
?>
Now here from the above code I get the image extracted, but after extraction the size of image is reduced to 61 bytes and is corrupt i.e. it cannot be viewed.
What could be wrong with this code please guide me
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您在这里混淆了客户端和服务器端。您根本无法创建 ZIP 客户端,因为 PHP 脚本是在服务器端执行的。因此,您要么必须指示用户在提交文件之前压缩文件,要么使用 ie。一个 Java 小程序,用于在上传之前为他们压缩文件。
I think you are confusing client-side and server-side here. You simply can't create a ZIP clientside, since the PHP script is executed on the server side. So you either have to instruct your users to zip the files before submitting them, or use ie. a Java applet to zip the file for them before uploading.
也许您想要的是:
您获得的 61 字节文件是您首先添加的文件!
给出
61
。Perhaps you wanted instead:
The 61-byte file you're getting is the one you added in the first place!
gives
61
.请检查下面的脚本,该脚本只会从 zip 文件中提取图像并排除所有其他文件。就像您可以添加所有其他 mime 类型一样。
Please check below script which will only extract images from zip file and exclude all other files. Like ways you can add all other mime type.