PHP将透明图片(PNG)合并到JPG背景图片上,实现PNG透明的效果
发表于:2023-01-04 23:15:06浏览:2386次
有二张图片,第一张为背景底图,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);
推荐文章
- layui.table 支持表格跨页多选的方法
- Gitee内的开源项目的指数是如何计算的?
- 2021年轻人熬夜报告:你每天熬夜都在干什么?
- php使用phpword的TemplateProcessor方式实现在word模板中动态插入表格
- phpstudy如何切换设置不同的composer版本及PHP版本
- ThinkPHP6防止XSS攻击的方案
- 支付宝已支持给微信QQ好友转账 微信支付宝互通何时能实现?
- JavaScript实现两个日期之间的工时计算,排除周末,每天工作日是8小时
- 82个常规的前端JavaScript方法封装(31~40)
- thinkphp6 leftjoin联表查询时,子表有多条记录去重后获取子表的最新记录查询方法

