Czechnology
Czechnology

Reputation: 14992

Convert image to string (for Symfony2 Response)

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?

Upvotes: 8

Views: 5051

Answers (1)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99909

Output buffering is probably the best solution.

BTW you can call one less function:

ob_start();
imagepng($img);
$str = ob_get_clean();

Upvotes: 7

Related Questions