将图像转换为字符串(对于Symfony2响应) [英] Convert image to string (for Symfony2 Response)

查看:120
本文介绍了将图像转换为字符串(对于Symfony2响应)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building a script for image resizing in Symfony2.

因为我希望能够使用标准的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()

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

...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]将图像保存到临时位置然后再次读取

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]使用输出缓冲

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

return new Response($str, 200, $headers);

有更好的方法吗?

推荐答案

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

Output buffering is probably the best solution.

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

BTW you can call one less function:

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

这篇关于将图像转换为字符串(对于Symfony2响应)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆