PHP GD: How to get imagedata as binary string?

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 );

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);

// ob_clean(); // optional
ob_start();
imagepng($imagedata);
$image = ob_get_clean();

Tags:

Php

Gd

Zip