当我尝试执行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);
答案 0 :(得分:2)
您的脚本存在许多问题:
$nome
中,但您正在打印$text
。$_POST['text']
是否存在,这可能会导致通知级错误。以下是您的代码示例,已修复:
// 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);
答案 1 :(得分:0)
了解更多: -
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);
?>