直接放代码,有需要优化的地方请各自进行优化:
/**
* 缩放并合成图片
* @desc: 函数用途描述信息
* @author: Sindsun
* @email: 2361313833@qq.com
* @date: 2019年7月13日
* @param $baseImagePath 主图,可以是远程图片
* @param: $fromImagePath 来源图片,可以是远程图片
* @param $pointX 要合并在上层的图片x位置
* @param $pointY 要合并在上层的图片y位置
* @param $topWith 指定在上层合并的图片的缩放后的大小
* @param $topHeight 指定在上层合并的图片的缩放后的高度
* @return
*/
public function compositeImage($baseImagePath, $fromImagePath, $pointX=0, $pointY=0, $topWith=0, $topHeight=0){
//背景图片对象
$baseImageInfo = getimagesize($baseImagePath);
$type = image_type_to_extension($baseImageInfo[2], false);
$imageCreateBaseFunc = "imagecreatefrom{$type}";
//设置两张图片对象
$baseImage = $imageCreateBaseFunc($baseImagePath);
//要合成的图修复对象
//获取图片信息
$fromImageInfo = getimagesize($fromImagePath);
if(!isset($fromImageInfo['bits']) || $fromImageInfo['bits'] <= 1024){
$fromImagePath = 'http://resource.test.com/avatar/default.png';
}
//如果图片不合格,使用默认的
$fromImageInfo = getimagesize($fromImagePath);
//获取图片类型,jpg等
$type = image_type_to_extension($fromImageInfo[2], false);
//获取相应方法
$imageCreateFromFunc = "imagecreatefrom{$type}";
$fromImage = $imageCreateFromFunc($fromImagePath);
//缩放图片
// 获取图像信息
list($bigWidth, $bigHight) = $fromImageInfo;
//图片缩放,可以根据原图片大小在这里计算等比缩放
$width = ($topWith == 0) ? 100 : $topWith;
$height = ($topHeight == 0) ? 100 : $topHeight;
// 创建缩略图画板
$newImage = imagecreatetruecolor($width, $height);
// 启用混色模式
imagealphablending($newImage, false);
// 保存PNG alpha通道信息
imagesavealpha($newImage, true);
//缩放
imagecopyresampled($newImage, $fromImage, 0, 0, 0, 0, $width, $height, $bigWidth, $bigHight);
//合成图片
//imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )---拷贝并合并图像的一部分
//将 src_im 图像中坐标从 src_x,src_y 开始,宽度为 src_w,高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x 和 dst_y 的位置上。两图像将根据 pct 来决定合并程度,其值范围从 0 到 100。当 pct = 0 时,实际上什么也没做,当为 100 时对于调色板图像本函数和 imagecopy() 完全一样,它对真彩色图像实现了 alpha 透明。
//imagecopymerge($baseImage, $fromImage, 0, 0, 0, 0, imagesx($fromImage), imagesy($fromImage), 100);
imagecopymerge($baseImage, $newImage, $pointX, $pointY, 0, 0, $width, $height, 100);
//向图片上写字
if(!empty($writeText)){
$penColor = imagecolorallocate($baseImage, 255, 255, 255);
//文件格式为gbk,而这里转为uft-8格式,才能正常输出,否则也为乱码。表示不明
$str = $writeText; //iconv("gb2312", "utf-8", $writeText);
$font = $this->RS_ROOT . 'fonts/SIMHEI.TTF';
imagettftext($baseImage, 46, 0, 210, 110, $penColor, $font, $str);
}
ob_clean();
header('Content-type:image/jpeg');
imagejpeg($baseImage) or die('创建图形失败');
}
版权声明: 此文为本站源创文章或由本站编辑从网络整理改编,
转载请备注出处: 狂码一生 http://www.sindsun.com/article-details-118.html[ ](https://cloud.tencent.com/developer/article/1552510)
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有