php头,内容类型png';不起作用


php header, content type png doesn't work

我很难处理php头,我试图在浏览器中创建任何类型的图像,而不将其保存在文件中,但无论我做什么,我都无法使其工作。

例如,如果我使用php手册中的这个基本示例:

$im = imagecreate(100, 100);
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

它会设置正确的标题,甚至在找不到图像时输出你得到的图标。

此外,我使用启用了GD的xampp,这是我的phpinfo GD部分:

GD Support  enabled
GD Version  bundled (2.0.34 compatible)
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.4.3
GIF Read Support    enabled
GIF Create Support  enabled
JPEG Support    enabled
libJPEG Version 6b
PNG Support enabled
libPNG Version  1.2.46
WBMP Support    enabled
XBM Support enabled

我的代码是错误的还是需要配置一些东西?

您不仅应该创建图像,还应该以某种方式填充图像:

error_reporting(E_ALL);
ini_set('display_errors', 1);
$im = imagecreate(100, 100) or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

PHP可能正在输出一条错误消息,从而扰乱了二进制图像数据。因此,在使用图像脚本时,我总是在PHP配置中禁用display_errors并启用log_errors;这样你就可以看到任何错误,而不会把输出搞砸。如果您确信没有PHP错误,请尝试将完整的脚本输出转储到一个文件中(脚本开头为ob_start();,结尾为file_put_contents("outfile", ob_get_clean());),并使用十六进制编辑器进行分析,看看是什么扰乱了PNG。