简体   繁体   English

如何使用PHP将zip存档中的图像写入文件

[英]How to write an image from a zip archive to file with PHP

I'm trying to extract an image from a zip archive and then write it to a file. 我正在尝试从zip存档中提取图像,然后将其写入文件。 Basically, my code is something like this (some bits were removed): 基本上,我的代码是这样的(一些位已删除):

while($zip_data = zip_read($zip))
       {
        $tfile = zip_entry_name($zip_data);
        if((substr($tfile, -11)  == "_screen.png") && (substr($tfile, 0, 8) == "template"))
         { 
          $screen = zip_entry_read($zip_data);
          $screen_name = $tfile;
         } 
        zip_entry_close($zip_data); 
       }

I successfully get the image inside the screen variable. 我成功地将图像获取到screen变量中。 However, I don't know how to write into an image file :| 但是,我不知道如何写入图像文件:|

I tried with file_put_contents and it generates me a blank image that has the correct size, but everything else is empty. 我尝试使用file_put_contents,它会生成一个具有正确大小的空白图像,但其他所有内容均为空。 I also tried with 我也尝试过

$screen_im = imagecreatefromstring($screen)

and then write screen_im with imagepng to a path but still no luck. 然后将带有imagepng的s​​creen_im写入路径,但仍然没有运气。 I don't really know what to do now. 我真的不知道该怎么办。 Simply unzipping the archive is not exactly what I need and since I seem to correctly read the image from the archive, there should be a way to write it into a new image 简单地解压缩档案文件并不是我真正需要的,并且由于我似乎可以正确地从档案文件中读取图像,因此应该有一种将其写入新图像的方法

Any help with this would be really apreciated 对此的任何帮助将不胜感激

You are not specifying the length to read, that's why only the initial data is read. 您没有指定要读取的长度,这就是为什么仅读取初始数据的原因。 From zip_entry_read doc : zip_entry_read doc

string zip_entry_read ( resource $zip_entry [, int $length ] )

length - The number of bytes to return. 长度 -的字节数返回。 If not specified, this function will attempt to read 1024 bytes. 如果未指定,此函数将尝试读取1024个字节。

You should provide the length of the file so it is read untill the end, not only the first KB. 您应该提供文件的长度,以便读取到最后,而不仅仅是第一个KB。 Or if the file is very big you should use a loop and fwrite 或者,如果文件很大,则应使用循环并执行fwrite

file_put_contents should work. file_put_contents应该可以工作。 If you open the resulting file in, say, Notepad, what does it look like? 如果您在记事本中打开生成的文件,它看起来像什么? And what does it look like if you manually extract it from the zip archive? 如果您从zip归档文件中手动提取它,它看起来像什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM