小编典典

在 PHP symfony 2 上渲染图像

php

我正在尝试使用 php-gd 生成图像,但输出只是特殊字符。我是否正确使用了“header(‘Content-Type: image/png’)”?

我的图像类:

public function __construct(){
    header('Content-Type: image/png');
    $this->image = imagecreate(200, 80);
    imagecolorallocate($this->image, 150, 150, 150);
    $textColor = imagecolorallocate($this->image, 255,255,255);
    imagestring($this->image, 28, 50, 55,rand(1000,9999), $textColor);
}

public function generateImage(){
    imagepng($this->image);
    imagedestroy($this->image);
}

我的默认控制器:

/**
 * @Route("/display-scorepng", name="scorepng")
 */
public function displayScorePng(){

    $test = new ImageController;
    return new Response("<h1>Hello World</h1> <br /><img src='" .$test->generateImage().  "' />");

}

感谢你的回复..


阅读 176

收藏
2022-07-25

共1个答案

小编典典

您混淆了我们所说的“显示图像”可能意味着的两个不同的东西:

  • 如果您在计算机上打开一个图像文件,您看到的只是该文件。应用程序将向您显示图像,没有其他内容。您可以在 Web 浏览器中打开一个图像文件,它会以这种方式显示它。
  • 如果您有一个 HTML 页面,则可以混合使用文本和对图像的引用。通过加载单独的图像文件并将其相对于其他内容定位在屏幕上,引用的每个图像都将显示为页面的一部分。

当您调用 时imagepng,它首先是“显示”图像 - 它正在生成图像的实际二进制数据,将其视为自己的文件。但是随后您将该函数与一些 HTML 混合在一起,试图在第二种意义上“显示”它。结果就像您在文本编辑器中打开了一个图像文件并将结果粘贴到 HTML 文件的中间一样。

您需要从此路线中删除所有提及的 HTML,然后输出图像。它的显示应该与您在 MS Paint 中创建并上传图像完全相同。然后,您可以通过 URL在 HTML 页面中引用它,就像您上传“真实”图像一样(到浏览器,它是真实的)。

/**
 * @Route("/display-scorepng", name="scorepng")
 */
public function displayScorePng(){   
    $test = new ImageController;
    // This function doesn't return anything, it just outputs:
    $test->generateImage();
    // Since the output is already done, we could just stop here
    exit;
}

完全在其他地方:

<p>This is an image: <img src="/display-scorepng" alt="something useful for blind folks"></p>
2022-07-25