You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP GD库图像绘制问题求助:代码输出与预期不符

排查PHP GD库绘图代码异常问题

我已在PHP中安装GD库,但运行代码后浏览器显示乱码无法识别图片,预期输出是包含两个矩形的150x150图片。

运行代码:

<?php 
//create the canvas
$myImage = ImageCreate(150,150);

//setup some colors
$black  = ImageColorAllocate($myImage, 0, 0, 0);
$white  = ImageColorAllocate($myImage, 255, 255, 255);
$red    = ImageColorAllocate($myImage, 255, 0, 0);
$green  = ImageColorAllocate($myImage, 0, 255, 0);
$blue   = ImageColorAllocate($myImage, 0, 0, 255);

//draw some rectangles
ImageRectangle($myImage, 15, 15, 55, 85, $red);
ImageRectangle($myImage, 55, 85, 125, 135, $white);

// output the image to the browser
header("Content-type: image/gif");
ImageGif($myImage);

//clean up after yourself
ImageDestroy($myImage);
?>

问题原因及解决方法:

  • 输出缓冲区污染:浏览器显示乱码是因为header()发送图片类型头之前,已有额外输出(比如文件开头的空格、UTF-8 BOM头,或代码中隐性输出),导致HTTP响应头被破坏。
    解决:将PHP文件保存为UTF-8无BOM编码,确保文件开头没有任何空格、换行;在header()前添加缓冲区清理代码:

    ob_clean();
    flush();
    header("Content-type: image/gif");
    
  • 画布初始化问题:ImageCreate()是GD旧版函数,在部分环境下可能出现颜色渲染异常,建议替换为ImageCreateTrueColor(),并手动填充背景色(该函数默认创建黑色画布):

    $myImage = ImageCreateTrueColor(150,150);
    ImageFill($myImage, 0, 0, $black); // 填充黑色背景,和原代码逻辑一致
    

内容的提问来源于stack exchange,提问作者Samuel Volder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 20:10:36