【问题标题】:'imagecreatefrompng' is outputting a crashed image'imagecreatefrompng' 正在输出崩溃的图像
【发布时间】:2012-07-30 13:19:07
【问题描述】:

当我尝试执行 imagecratefrompng 时,我遇到了 PHP 中的 gd 库问题。我正在运行一个脚本,用户输入文本并将其添加到预先创建的图像中。问题是,当我输出图像时,图像显示为损坏。

如果我的脚本/图像有问题,谁能帮忙指点?

图片为 PNG,600x956,220kb 文件大小。

GD 库已启用。已启用 PNG、JPEG、GIF 支持。

这里是代码。

// Text inputed by user
  $text = $_POST['text'];
// Postion of text inputed by the user
  $text_x = 50;
  $text_y = 817;
// Color of the text
  $text_color = imagecolorallocate($img, 0, 0, 0);
// Name of the file (That is in the same directory of the PHP file)
  $nomeDaImagem = "Example";


$img = imagecreatefrompng($nomeDaImagem);

//Text is retrieved by Post method
imagestring($img, 3, $text_x, $text_y, $text, $text_color);

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

imagedestroy($img);

【问题讨论】:

  • 你永远不会使用你的变量 $nome$text 在你的脚本中是未定义的。是在别处定义的吗?
  • 这是一个输出错误。 $nome 应该是 $text。我会改正的。

标签: php png gd


【解决方案1】:

您的脚本存在许多问题:

  1. 您在实际创建图像之前尝试为图像分配颜色。
  2. 您要写入的字符串在变量$nome 中,但您正在打印$text
  3. 您不检查$_POST['text'] 是否存在,这可能会导致通知级错误。
  4. 您不检查文件是否存在,这可能会导致警告级错误。

这是您的代码示例,已修复:

// Text inputed by user 
  $nome = isset($_POST['text']) ? $_POST['text'] : "<Nothing to write>"; 
// Postion of text inputed by the user 
  $text_x = 50; 
  $text_y = 817; 
// Name of the file (That is in the same directory of the PHP file) 
  $nomeDaImagem = "Example"; 

$img = file_exists($nomeDaImagem)
   ? imagecreatefrompng($nomeDaImagem)
   : imagecreate(imagefontwidth(3)*strlen($nome)+$text_x,imagefontheight(3)+$text_y);

// Color of the text 
  $text_color = imagecolorallocate($img, 0, 0, 0); 
//Text is retrieved by Post method 
imagestring($img, 3, $text_x, $text_y, $nome, $text_color); 

header("Content-type: image/png"); 
imagepng($img); 
imagedestroy($img); 

【讨论】:

  • 感谢您的回复。我确实尝试了您的代码,但图像仍然损坏。我还尝试使用来自 PHP 页面的示例 Abid(右下方)的代码,它也输出了损坏的图像。我认为问题出在“imagecreatfrompng”中。也许我没有正确编写路径($nomeDaImagem 字符串)。
  • 对不起,这么久了,我确实发现了问题:imagecreatefrompng 必须有它的价值,最后是“.png”。反正。再次感谢您的帮助。
【解决方案2】:

阅读更多:--

http://php.net/manual/en/function.imagecreatefrompng.php

http://www.php.net/manual/en/function.imagecreatefromstring.php

或者试试这个

<?php
function LoadPNG($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefrompng($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a blank image */
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);

        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/png');

$img = LoadPNG('bogus.image');

imagepng($img);
imagedestroy($img);
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多