因为客户上传的商品图大小不一,所以加了一个原图裁剪方法 mkThumbnail (代码参考另一篇文章 https://www.cnblogs.com/gyrgyr/p/13726317.html )
生成图示例:(背景尺寸1066*1599)
public function getActivityImg($logo='',$template,$url,$goods_info) { $price = empty($goods_info['sg_vip_price']) || $goods_info['sg_vip_price']==0 ?$goods_info['sg_price']:$goods_info['sg_vip_price']; //商品价格 $QR = "base.png"; $last = "last.png"; $errorCorrectionLevel = 'Q'; //防错等级 $matrixPointSize = 3; //二维码大小 //二维码位置 $x = 815; $y = 625; //生成二维码 //参数内容:二维码储存内容,生成存储,防错等级,二维码大小,白边大小 Vendor('phpqrcode.phpqrcode'); $object = new QRcode(); $object->png($url, $QR, $errorCorrectionLevel, $matrixPointSize, 1); $last = $QR; //合成二维码图片跟 模板图片 $path_1 = $template; //背景图 $path_2 = $last; //二维码图 $dst = imagecreatefromstring(file_get_contents($path_1)); $src = imagecreatefromstring(file_get_contents($path_2)); list($src_w, $src_h) = getimagesize($path_2); imagecopymerge($dst, $src, $x, $y, 0, 0, $src_w, $src_h, 100); //商品图片缩放为新图片 $EchoPath='./share_cod/-'.rand(99).time().'.png'; $r = $this->mkThumbnail($goods_info['sg_img_url'],'418','408',$EchoPath); //商品图位置 $goods_x = 176; $goods_y = 937; //合并商品图 与 二维码带背景 $path_2 = $EchoPath; //商品图 $src = imagecreatefromstring(file_get_contents($path_2)); list($src_w, $src_h) = getimagesize($path_2); imagecopymerge($dst, $src, $goods_x, $goods_y, 0, 0, $src_w, $src_h, 100); //打上文字 商品名称 $font = '/usr/share/fonts/chinese/msyhbd.ttf'; $g_name = mb_substr($goods_info['sg_name'],0,10,'utf-8').'...'; /*
这块注释的是原来设计图文字是居中的,具体文字数量不确定,所以计算的居中位置,后来改为靠右,有了具体尺寸就不用了
$fontBox = imagettfbbox(33, 0, $font, $g_name); $textx = ceil((896 - $fontBox[2]) / 2 ); //计算居中位置 $black = imagecolorallocate($dst, 0x00, 0x00, 0x00);//字体 $black = imagecolorallocate($dst, 0x00, 0x00, 0x00);//字体 imagefttext($dst, 33, 0, $textx, 290, $black, $font, $g_name);//字体颜色 */ $black = imagecolorallocate($dst, 254, 243, 222);//字体 imagefttext($dst, 50, 0, 370, 270, $black, $font, $g_name);//字体颜色 //打上文字 原价 $black = imagecolorallocate($dst, 231,162,115);//字体 imagefttext($dst, 30, 0, 552, 388, $black, $font, intval($goods_info['sg_y_price']));//字体颜色 //打上文字 价格 $black = imagecolorallocate($dst, 255,255,255);//字体 imagefttext($dst, 35, 0, 810, 388, $black, $font, intval($price));//字体颜色 //打上文字 卖点 $black = imagecolorallocate($dst, 255, 255, 255);//字体 imagefttext($dst, 38, 0, 399, 530, $black, $font, $goods_info['sg_describe']);//字体颜色 //输出图片 list($dst_w, $dst_h, $dst_type) = getimagesize($path_1); switch ($dst_type) { case 1://GIF $typ = 'gif'; break; case 2://JPG $typ = 'jpg'; break; case 3://PNG $typ = 'png'; break; default: break; } //输出到本地文件夹,返回生成图片的路径 $fileName= get_mpid().'_'.$goods_info['sg_id'].time(); $EchoPath='./Images/share_img/'.$fileName.'.'.$typ; imagepng($dst,$EchoPath); imagedestroy($dst); imagedestroy($src); return $EchoPath; }