学习笔记

PHP将透明图片(PNG)合并到JPG背景图片上,实现PNG透明的效果

2023-09-08 11:47:25 juzhen 1


有二张图片,第一张为背景底图,jpg格式;第二张为放在背景图片上的图片,png格式,有一部分是透明的。
现在需要实现的效果是将png格式图片放到背景图片上,png格式图片透明的部分要透明。代码其实很简单,最关键的地方就是一定要用imagecopy这个函数。

具体代码如下:

<?php
//背景图片路径
$srcurl = './img/bg.jpg';
//目标图片路径
$desurl = './img/dot.png';

//创建源图的实例
$src = imagecreatefromstring(file_get_contents($srcurl));
//创建点的实例
$des = imagecreatefrompng($desurl);
//获取点图片的宽高
list($point_w, $point_h) = getimagesize($desurl);

//重点:png透明用这个函数
imagecopy($src, $des, 970, 1010, 0, 0, $point_w, $point_h);
imagecopy($src, $des, 930, 1310, 0, 0, $point_w, $point_h);

header('Content-Type: image/jpeg');
imagejpeg($src);
imagedestroy($src);
imagedestroy($des);?>

关于imagecopy函数说明:

bool imagecopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )

将 src_im 图像中坐标从 src_x,src_y 开始,宽度为 src_w,高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x 和 dst_y 的位置上。

如果没有使用imagecopy函数而是用了imagecopymerge函数,就会导致目标图片透明的地方不透明了。

另外,PHP把文字写到背景图片的代码:

$link_url = "/storage/avatars/certificate_" . time() . "png";

$real_url = CMS_ROOT . "public" . $link_url;

$bg_path = CMS_ROOT . "public/static/home/images/bg.jpg"; //背景图片路径

//创建图片的实例

$bg = imagecreatefromstring(file_get_contents($bg_path));

//字体文件

$font_file = CMS_ROOT . "public/static/home/file/msyh.ttf";

$font_file_bold = CMS_ROOT . "public/static/home/file/msyh_bold.ttf";

//设定字体的颜色

$font_color_black = ImageColorAllocate($bg, 51, 51, 51);

$font_color_gray = ImageColorAllocate($bg, 120, 120, 120);

$font_color_blue = ImageColorAllocate($bg, 32, 39, 92);

$font_color_red = ImageColorAllocate($bg, 192, 69, 59);


//绘制文字

//获取文字所需的尺寸大小

$nameBox = imagettfbbox(58, 0, $font_file_bold, '我是文字内容');

//计算居中位置

$x_name = (1000 - $nameBox[2]) / 2;

imagettftext($bg, 58, 0,(int)$x_name, 100, $font_color_black, $font_file_bold, $certificate['name']);


//输出图片

if ($real_url) {

    imagepng($bg, $real_url);

} else {

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

    imagepng($bg);

}

//释放空间

imagedestroy($bg);

// 设置300秒有效期

return download($real_url,$user['name'].'_'.$code.'.png')->expire(300);

//$this->apiSuccess($real_url);


首页
产品
新闻
联系