【发布时间】:2018-04-07 05:32:21
【问题描述】:
我正在使用此代码在核心 PHP 中创建图像
header ("Content-type: image/png");
$text='test@example.com';
$string = $text;
$font = 3;
$width = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);
$im = @imagecreate ($width,$height);
$background_color = imagecolorallocate ($im, 255, 255, 255); //white background
$text_color = imagecolorallocate ($im, 0, 0,0);//black text
imagestring ($im, $font, 0, 0, $string, $text_color);
echo imagepng ($im);
上面的代码在核心 PHP 文件中运行良好,但现在我正在使用 laravel 框架中的项目。我对 laravel 完全陌生。当我在 laravel 中尝试相同的代码时,它不起作用。我尝试更改响应方法但仍然失败 这是我尝试过的。
public function imgCreate(){
header ("Content-type: image/png");
$text='test@example.com';
$string = $text;
$font = 3;
$width = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);
$im = @imagecreate ($width,$height);
$background_color = imagecolorallocate ($im, 255, 255, 255); //white background
$text_color = imagecolorallocate ($im, 0, 0,0);//black text
imagestring ($im, $font, 0, 0, $string, $text_color);
echo imagepng($im);
//return response($im)->withHeaders(['Content-type'=>'image/png']);
}
所以基本上,我在控制器函数 (imgCreate) 中粘贴了相同的代码。我尝试了不同的响应方法似乎都有错误 当我这样回来时
//echo imagepng($im);
return response($im)->withHeaders(['Content-type'=>'image/png']);
它抛出一个错误 “响应内容必须是实现__toString()的字符串或对象,“resource”给定。”
当我尝试简单的方法时
echo imagepng($im);
//return response($im)->withHeaders(['Content-type'=>'image/png']);
我得到一个像这样的不可读字符串:-
".PNG IHDRp K.xPLTE..U......~.IDAT.c0S �� ��q��������67?>�/�Ð8ۘ��f��3�%Hn�cH���}����H� �riggc�0Ncȝm�qss��ǒ%7�1X||x����l����ripW400#; �^10��.IEND.B`.1"
是否可以从 laravel 中的文本创建图像?还是我做错了什么? 在我看来,问题似乎是标题“Content-type”,它负责以图像的形式返回结果。
提前致谢!!!!!!
【问题讨论】:
-
@JitendraSoftgrid "Json" 用于以完全脱离上下文的 Json 对象的形式发送响应