【问题标题】:PHP issue with imagepng showing broken image显示损坏图像的imagepng的PHP问题
【发布时间】:2012-08-17 18:37:03
【问题描述】:

我正在尝试创建一个还缓存图像的动态图像生成器。

一切正常,除了由于某种原因,当我保存图像并尝试同时显示它时,它显示一个损坏的图像图标(如:http://cl.ly/image/3K1f0R0n1R0U)。

代码示例:

// some string parsing junk happens up here, but removing that didn't change 
// what I've been having a problem with

header("Content-type: image/png;");

if(file_exists($fullFileName)){ // serve the file if it already exists
    ob_clean();
    flush();
    readfile($fullFileName);
    exit;
} else { // create the file if it doesn't exist
    $my_img = imagecreate(200, 80);
    $background = imagecolorallocatealpha($my_img, 0, 0, 0, 127);
    $line_colour = imagecolorallocatealpha($my_img, $color["r"], $color["g"], $color["b"], $color["a"]);

    imagesetthickness($my_img, 1);
    imageline($my_img, 30, 45, 165, 45, $line_colour);

    //////////////////////////////////////////
    // the line that's causing my troubles: //
    //////////////////////////////////////////
    imagepng($my_img, $fullFileName);


    imagecolordeallocate($line_color);
    imagecolordeallocate($background);
    imagedestroy($my_img);
}

所以,图像创建得很好,保存得很好,并且在我刷新页面时完全按照我想要的方式显示(因为它会抓取保存的文件)。

如果我把上面那条该死的线切换到:

imagepng($my_img);

然后图像显示正常,但没有保存(因为我没有告诉它)。

我以为这个话题:

PHP echoing jpeg image fails, but writing same image to file works great. Why?

听起来很相似,但删除尾随空格仍然没有改变正在发生的事情。其他线程提到它可能是在标题之前发送的其他内容的问题,但在这个文件中没有类似的东西。

对可能出现的问题有任何想法吗?没有记录任何错误,我没有想法。

谢谢!

-扎克

编辑:

有人解释说我正在破坏我的形象,但我错过了。我最终使用了这个:

header("Content-type: image/png");

if(!file_exists($fullFileName)) {
    $my_img = imagecreate($dashWidth + $dashSpace, $height);
    $background = imagecolorallocatealpha($my_img, 0, 0, 0, 127);
    $line_colour = imagecolorallocatealpha($my_img, $color["r"], $color["g"], $color["b"], $color["a"]);

    imagesetthickness($my_img, 1);
    imageline($my_img, 0, $height-1, $dashWidth-1, $height-1, $line_colour);

    imagepng($my_img, $fullFileName);
    imagecolordeallocate($my_img, $line_color);
    imagecolordeallocate($my_img, $background);
}

ob_clean();
flush();
readfile($fullFileName);
exit;

【问题讨论】:

    标签: php broken-image


    【解决方案1】:

    你是说

    header("Content-type: image/png"); // without ;
    

    而且,您正在破坏您的图像,请再次读取文件

    readfile($fullFileName);
    

    因为imagepng($my_img, $fullFileName); 只保存它。

    【讨论】:

    • 既然您已经解释过了,那就完全合情合理了。我对 PHP 非常陌生,所以从网上抓取随机脚本并尝试将它们修补在一起会导致这样的问题。我会更新我的帖子,包括你的答案。谢谢!
    【解决方案2】:

    来自手册,imagepng

    输出从给定图像保存PNG图像

    注意“或”。尝试拨打两个电话到imagepng。一次调用将其保存到文件,一次调用不带文件名参数将图像输出到浏览器。

    【讨论】:

    • 我一定已经读了五遍了,有些还是没有抓住“或”。现在这是有道理的。谢谢!
    【解决方案3】:

    尝试使用文本编辑器打开图像。 关闭 error_reporting。 显示损坏的图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 2018-05-05
      • 2015-06-11
      相关资源
      最近更新 更多