首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“‘imagecreatefrompng”正在输出崩溃的图像

“‘imagecreatefrompng”正在输出崩溃的图像
EN

Stack Overflow用户
提问于 2012-07-30 21:19:07
回答 2查看 2K关注 0票数 0

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

如果我的脚本/图像出了什么问题,有人能帮我指出吗?

该图像为PNG格式,600x956,220kb文件大小。

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

下面是代码。

代码语言:javascript
复制
// 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);
EN

回答 2

Stack Overflow用户

发布于 2012-07-30 21:31:04

您的脚本存在许多问题:

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

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

代码语言:javascript
复制
// 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); 
票数 2
EN

Stack Overflow用户

发布于 2012-07-30 21:25:29

阅读更多:--

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

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

或者试试这个

代码语言:javascript
复制
<?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);
?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11722428

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档