简体   繁体   中英

PHP imagejpeg - convert output to base64

I am generating a simple text in an image like this...

// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');

// Output the image
imagejpeg($im);

// Free up memory
imagedestroy($im);

I need the output as a base64 string, I have tried base64_encode($im) but it is not working correctly for me.

Does anybody have an example I can see?

Try using the ob_get_clean function to get the image from the output buffer and then encode it to base64:

// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

ob_start();

// Output the image
imagejpeg($im);

$img = ob_get_clean();
ob_end_clean();

// Free up memory
imagedestroy($im);

echo base64_encode($img);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM