I have an image variable,
$im = imagecreatetruecolor(400, 300);
Is there anyway to get a string of binary of this image in jpeg format without saving it to a file? Thanks!
Yes, this is possible (even without output buffering). It's undocumented as it seems, but you can pass a stream resource instead of a file name.
<?php
$stream = fopen("php://memory", "w+");
$i = imagecreatetruecolor(200, 200);
imagepng($i, $stream);
rewind($stream);
$png = stream_get_contents($stream);
ob_start();
imagejpeg($im);
$imageString = ob_get_clean();
As a function and adding imagedestroy()
.
function imagejpeg_tostring($im,$quality=75) {
ob_start(); //Stdout --> buffer
imagejpeg($im,NULL,$quality); // output ...
$imgString = ob_get_contents(); //store stdout in $imgString
ob_end_clean(); //clear buffer
imagedestroy($im); //destroy img
return $imgString;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With