BBog
BBog

Reputation: 3650

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. 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. 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. I also tried with


    $screen_im = imagecreatefromstring($screen) 

and then write screen_im with imagepng to a path but still no luck. 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

Upvotes: 0

Views: 455

Answers (2)

MeLight
MeLight

Reputation: 5555

You are not specifying the length to read, that's why only the initial data is read. From 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.

You should provide the length of the file so it is read untill the end, not only the first KB. Or if the file is very big you should use a loop and fwrite

Upvotes: 2

CodeCaster
CodeCaster

Reputation: 151588

file_put_contents should work. 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?

Upvotes: 1

Related Questions