下面是WORKS(挖它从我3岁的档案了)代码。我用它来组合2个PNG图像并渲染一些文本,同时保持透明度。它会创建一个新图像,设置透明度颜色,然后将图像复制到其中。这个确切的文件在我的实现中起作用(我现在编写的颜色,因为那时我从数据库中提取它们,所以我没有记忆它们是什么,它们是什么意思)。对不起,如果它很混乱。生成的图像是$image
,它由作为第一层的$ruler_img
,作为第二层的$index_img
和作为第三层的文本组成。你的情况只有一层。
//prepare first layer
$ruler_img=$ruler_img=imagecreatefrompng($_SERVER['DOCUMENT_ROOT'].$ruler['out_ruler_img']);
//create main image, basic layer, background
$image = imageCreateTrueColor($ruler_width, $ruler_height);
imageSaveAlpha($image, true);
$transparentColor = imagecolorallocatealpha($image, 0,0,0, 127); //some color used as transparency key, this uses black
$color = imagecolorallocatealpha($image, 0,0,0,127);
//fill with transparent color
imagefill($image, 0, 0, $transparentColor);
imagealphablending($ruler_img,true);
//copy the first layer
imagecopy($image,$ruler_img,0,0,0,0,$ruler_width,$ruler_height);
//prepare the second layer
$index_img=imagecreatefrompng($_SERVER['DOCUMENT_ROOT'].$ruler['out_index_img']);
$size=getimagesize($_SERVER['DOCUMENT_ROOT'].$ruler['out_index_img']);
$index_width=$size[0];
$index_height=$size[1];
imagealphablending($index_img,true);
$ratio=1.0;
if($index_height>$ruler_height)
$ratio=$ruler_height*1.0/$index_height;
$new_width=$index_width*$ratio;
$new_height=$index_height*$ratio;
//now I copy the resampled second layer
imagecopyresampled(
$image,
$index_img,
$position*($ruler_width-$new_width),
($ruler_height-$new_height)/2,
0,
0,
$new_width,
$new_height,
$index_width,
$index_height);
//render text
$font = "fonts/comic.ttf";
$fontSize=10;
$box=imagettfbbox($fontSize, 0, $font,$text);
$textWidth=$box[2]-$box[6];
$textHeight=$box[3]-$box[7];
imagettftext($image, $fontSize, 0, $ruler_width-$textWidth-10, $ruler_height+12, $color, $font, $text);
header("Content-type: image/png");
//that's it!
imagepng($image);
这很简单,完美无瑕。谢谢。 –