PHP SLIM:如何返回动态生成的图像

我正在尝试从SLIM控制器显示动态生成的图像,但我得到一个空白屏幕。

谢谢。</ p>

  public function textToImage($ request,$ response,$ args){

//要绘制的文字
$ text =“Hello World” ;
$ length = strlen($ text);
//创建图像

$ im = imagecreatetruecolor($ length * 12,30);

//创建一些颜色
$ white = imagecolorallocate($ im,255,255,255);
$ gray = imagecolorallocate($ im,128,128,128);
$ black = imagecolorallocate($ im,44,62,80);
$ boxcolor = imagecolorallocate($ im,95,128,149);

$ font ='Helvetica.ttf';
imagefilledrectangle($ im,0,0,$ length * 9 + $ capitaladjust,29,$ white) ;
imagettftext($ im,13,0,0,20,$ black,$ font,$ text);

$ response-&gt; getBody() - &gt; write(base64_encode($ im));

$ response = $ response-&gt; withHeader('Content-type','image / png');

返回$ response;
}
</ code> </ pre>
</ div>

展开原文

原文

I am trying to display a dynamically generated image from SLIM controller but I am getting a blank screen. Thanks.

public function textToImage($request, $response, $args) {

    // The text to draw
    $text = "Hello World";
    $length=strlen($text);
    // Create the image

    $im = imagecreatetruecolor($length*12, 30);

    // Create some colors
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 44, 62, 80);
    $boxcolor=imagecolorallocate($im, 95, 128, 149);

    $font = 'Helvetica.ttf';
    imagefilledrectangle($im, 0, 0, $length*9+$capitaladjust, 29, $white);
    imagettftext($im, 13, 0, 0, 20, $black, $font, $text);

    $response->getBody()->write(base64_encode($im));
    $response = $response->withHeader('Content-type', 'image/png');     
    return $response;
 }

1个回答



base64编码 $ im </ code>不会创建有效的PNG文件。 尝试使用 imgpng ,然后发送它创建的PNG文件的原始内容。</ p>

代码看起来像这样:</ p>

  ob_start(); 
imagepng($ im);
$ data = ob_get_contents();
ob_end_clean();

$ response-&gt; getBody() - &gt; write($ data);
$ response = $ response-&gt; withHeader('Content-type',' 图像/ PNG');

return $ response;
</ code> </ pre>
</ div>

展开原文

原文

base64 encoding $im will not create a valid PNG file. Try using imgpng and then sending the raw contents of the PNG file that it creates.

The code would look something like this:

ob_start();
imagepng($im);
$data = ob_get_contents();
ob_end_clean();

$response->getBody()->write($data);
$response = $response->withHeader('Content-type', 'image/png');     
return $response;

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐