I'm building a script for image resizing in Symfony2.
As I'd like to be able to use standard Symfony2 response system...
$headers = array('Content-Type' => 'image/png',
'Content-Disposition' => 'inline; filename="image.png"');
return new Response($img, 200, $headers); // $img comes from imagecreatetruecolor()
...I need a string to send as a response. Unfortunately, functions like imagepng
do only write files or output directly to the browser, not return strings.
So far the only solutions I was able to think of are
1] save the image to a temporary location and then read it again
imagepng($img, $path);
return new Response(file_get_contents($path), 200, $headers);
2] use output buffering
ob_start();
imagepng($img);
$str = ob_get_contents();
ob_end_clean();
return new Response($str, 200, $headers);
Is there a better way?
Output buffering is probably the best solution.
BTW you can call one less function:
ob_start();
imagepng($img);
$str = ob_get_clean();
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