Convert image to string (for Symfony2 Response)

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

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?

回答1:

Output buffering is probably the best solution.

BTW you can call one less function:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!