Convert GD output to base64

user862010 picture user862010 · Dec 18, 2011 · Viewed 19.5k times · Source

Well, my question is very simple, i just wanna convert the output of imagepng/imagejpg to base64, how i can do this ? the correctly way is with capturing output buffer ? thanks.

Answer

Filip Roséen - refp picture Filip Roséen - refp · Dec 18, 2011

imagejpeg/imagepng doesn't return any data, they write the image data directly to the output stream (or to a file).

If you'd like to capture this data encoded as base64 the easiest method is to use PHPs Output Control Functions, and then use base64_encode on the $image_data.

ob_start (); 

  imagejpeg ($img);
  $image_data = ob_get_contents (); 

ob_end_clean (); 

$image_data_base64 = base64_encode ($image_data);