34

I'm using a solution for assembling image files to a zip and streaming it to browser/Flex application. (ZipStream by Paul Duncan, http://pablotron.org/software/zipstream-php/).

Just loading the image files and compressing them works fine. Here's the core for compressing a file:

// Reading the file and converting to string data
$stringdata = file_get_contents($imagefile);

// Compressing the string data
$zdata = gzdeflate($stringdata );

My problem is that I want to process the image using GD before compressing it. Therefore I need a solution for converting the image data (imagecreatefrompng) to string data format:

// Reading the file as GD image data
$imagedata = imagecreatefrompng($imagefile);
// Do some GD processing: Adding watermarks etc. No problem here...

// HOW TO DO THIS??? 
// convert the $imagedata to $stringdata - PROBLEM!

// Compressing the string data
$zdata = gzdeflate($stringdata );

Any clues?

Cambiata
  • 3,705
  • 9
  • 35
  • 45

3 Answers3

51

One way is to tell GD to output the image, then use PHP buffering to capture it to a string:

$imagedata = imagecreatefrompng($imagefile);
ob_start();
imagepng($imagedata);
$stringdata = ob_get_contents(); // read from buffer
ob_end_clean(); // delete buffer
$zdata = gzdeflate($stringdata);
spoulson
  • 21,335
  • 15
  • 77
  • 102
  • I tried this and for some reason it fails with nested `ob_start`. I found M.i.X's answer below to be a better solution. – supersan Dec 27 '20 at 09:28
22
// ob_clean(); // optional
ob_start();
imagepng($imagedata);
$image = ob_get_clean();
Stefan Brinkmann
  • 965
  • 8
  • 11
  • 1
    ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean(), so this solution is slightly more elegant that the accepted answer above. – Kenneth Vogt Sep 12 '16 at 23:34
19

The php://memory stream can be used when output-buffer juggling is unwanted. https://www.php.net/manual/en/wrappers.php.php

$imagedata = imagecreatefrompng($imagefile);

// processing

$stream = fopen('php://memory','r+');
imagepng($imagedata,$stream);
rewind($stream);
$stringdata = stream_get_contents($stream);

// Compressing the string data
$zdata = gzdeflate($stringdata );
M.i.X
  • 275
  • 2
  • 6