Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert image to string (for Symfony2 Response)

Tags:

php

image

symfony

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?

like image 497
Czechnology Avatar asked Sep 09 '11 18:09

Czechnology


1 Answers

Output buffering is probably the best solution.

BTW you can call one less function:

ob_start();
imagepng($img);
$str = ob_get_clean();
like image 85
Arnaud Le Blanc Avatar answered Oct 23 '22 03:10

Arnaud Le Blanc