当我尝试从PHP执行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);发布于 2012-07-30 21:31:04
您的脚本存在许多问题:
$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); 发布于 2012-07-30 21:25:29
阅读更多:--
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);
?>https://stackoverflow.com/questions/11722428
复制相似问题