将图像转换为字符串(对于Symfony2响应)

Cze*_*ogy 8 php image symfony

我正在为Symfony2中的图像大小调整构建一个脚本.

因为我希望能够使用标准的Symfony2响应系统......

$headers = array('Content-Type'     => 'image/png',
                 'Content-Disposition' => 'inline; filename="image.png"');

return new Response($img, 200, $headers);  // $img comes from imagecreatetruecolor()
Run Code Online (Sandbox Code Playgroud)

...我需要一个字符串作为回复发送.不幸的是,像imagepngdo这样的函数只会将文件或输出直接写入浏览器,而不是返回字符串.

到目前为止,我能想到的唯一解决方案是

1]将图像保存到临时位置,然后再次读取

imagepng($img, $path);
return new Response(file_get_contents($path), 200, $headers);
Run Code Online (Sandbox Code Playgroud)

2]使用输出缓冲

ob_start();
imagepng($img);
$str = ob_get_contents();
ob_end_clean();

return new Response($str, 200, $headers);
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

Arn*_*anc 7

输出缓冲可能是最好的解决方案.

顺便说一句,你可以减少一个功能:

ob_start();
imagepng($img);
$str = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)