Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php : How to create a string of image binary without saving it to a file?

Tags:

php

jpeg

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!

like image 512
user1519831 Avatar asked Jul 12 '12 06:07

user1519831


3 Answers

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);
like image 190
kelunik Avatar answered Nov 03 '22 03:11

kelunik


ob_start();
imagejpeg($im);
$imageString = ob_get_clean();
like image 35
deceze Avatar answered Nov 03 '22 02:11

deceze


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;
}
like image 42
Peter Krauss Avatar answered Nov 03 '22 04:11

Peter Krauss