ImageMagick 显示乱码文本而不是图像

ImageMagick displays garbled text instead of image

我正在尝试在 PHP 中使用 ImageMagick class 函数。 为了熟悉 ImageMagick,我在 PHP 中写了几行代码以在我的浏览器中显示一个红色方块。

我没有显示红色方块,而是显示乱码。 我知道 ImageMagick 已安装,因为我可以使用 ImageMagick 函数将红色方块保存到文件中。

在此先感谢您对 ImageMagick 和 Whosebug 新手的帮助!

这是我的 PHP 代码:

$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');
$image->writeImage("MyOutput.png");

header('Content-type: image/png');
echo $image;  //This causes just raw text to be displayed. :(

echo '<img src=MyOutput.png>'; //Displays a 100x100 red image!
                               //..So, ImageMagick IS installed.

这是我的完整 PHP 文件。

<!DOCTYPE html>
<head>
    <title>ImageMagick Test</title>
</head>
<body>
<?php

$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');

header('Content-type: image/png');
echo $image;
?>

</body>
</html>

您遇到的主要问题是您在输入一些输出后发送 Content-Type: image/png。放置任何输出后,PHP 立即发送所有响应 headers 并继续响应的 body 部分。大多数服务器上的默认 Content-Typetext/html,因此您的浏览器将图像内容解释为 HTML,这就是您看到一些垃圾的原因。有点像用记事本打开PNG文件

See this question for more information about sending response headers

此外,您不能 return HTML 和图像内容根据一个请求,所以 不要在您的 HTML =33=] 文件。该图像是独立文件,必须根据自己的单独请求 return 编辑,仅包含 headers、图像字节,仅此而已。

这应该有效:

<?php
$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');

header('Content-type: image/png');
echo $image;

请注意,这是整个 PHP 文件,您不能从 <?php ?> 外部或通过回显发送任何其他输出。

如果你想将你的图像包含到 HTML 中,你需要第二个文件(它可能是普通的 HTML),它应该如下所示:

<!DOCTYPE html>
<head>
    <title>ImageMagick Test</title>
</head>
<body>
    <!-- here we're including our image-generating PHP script -->
    <img src="imagickTest.php">
</body>
</html>

然后,如果您只想查看图像,则可以参考 PHP 文件;如果您希望将图像放入 HTML 上下文中,则可以参考 HTML 文件。