最近工作需求需要生成分享图片,最初用js的html2canvas截图插件各种问题,后来干脆PHP的PG库在后台生成图片,很愉快的解决了各种问题,我们要实现的效果如下图:
假设代码中用到的资源文件夹在当前code_png目录下:
/** * 分享图片生成 * @param $gData 商品数据,array * @param $codeName 二维码图片 * @param $fileName string 保存文件名,默认空则直接输入图片 */ function createSharePng($gData,$codeName,$fileName = ''){ //创建画布 $im = imagecreatetruecolor(618, 1000); //填充画布背景色 $color = imagecolorallocate($im, 255, 255, 255); imagefill($im, 0, 0, $color); //字体文件 $font_file = "code_png/msyh.ttf"; $font_file_bold = "code_png/msyh_bold.ttf"; //设定字体的颜色 $font_color_1 = ImageColorAllocate ($im, 140, 140, 140); $font_color_2 = ImageColorAllocate ($im, 28, 28, 28); $font_color_3 = ImageColorAllocate ($im, 129, 129, 129); $font_color_red = ImageColorAllocate ($im, 217, 45, 32); $fang_bg_color = ImageColorAllocate ($im, 254, 216, 217); //Logo list($l_w,$l_h) = getimagesize('code_png/logo100_100.png'); $logoImg = @imagecreatefrompng('code_png/logo100_100.png'); imagecopyresized($im, $logoImg, 274, 28, 0, 0, 70, 70, $l_w, $l_h); //温馨提示 imagettftext($im, 14,0, 100, 130, $font_color_1 ,$font_file, '温馨提示:喜欢长按图片识别二维码即可前往购买'); //商品图片 list($g_w,$g_h) = getimagesize($gData['pic']); $goodImg = createImageFromFile($gData['pic']); imagecopyresized($im, $goodImg, 0, 185, 0, 0, 618, 618, $g_w, $g_h); //二维码 list($code_w,$code_h) = getimagesize($codeName); $codeImg = createImageFromFile($codeName); imagecopyresized($im, $codeImg, 440, 820, 0, 0, 170, 170, $code_w, $code_h); //商品描述 $theTitle = cn_row_substr($gData['title'],2,19); imagettftext($im, 14,0, 8, 845, $font_color_2 ,$font_file, $theTitle[1]); imagettftext($im, 14,0, 8, 875, $font_color_2 ,$font_file, $theTitle[2]); imagettftext($im, 14,0, 8, 935, $font_color_2 ,$font_file, "券后价¥"); imagettftext($im, 28,0, 80, 935, $font_color_red ,$font_file_bold, $gData["price"]); imagettftext($im, 14,0, 8,970, $font_color_3 ,$font_file, "现价¥".$gData["original_price"]); //优惠券 if($gData['coupon_price']){ imagerectangle ($im, 125 , 950 , 160 , 975 , $font_color_3); imagefilledrectangle ($im, 126 , 951 , 159 , 974 , $fang_bg_color); imagettftext($im, 14,0, 135,970, $font_color_3 ,$font_file, "券"); $coupon_price = strval($gData['coupon_price']); imagerectangle ($im, 160 , 950 , 198 + (strlen($coupon_price)* 10), 975 , $font_color_3); imagettftext($im, 14,0, 170,970, $font_color_3 ,$font_file, $coupon_price."元"); } //输出图片 if($fileName){ imagepng ($im,$fileName); }else{ Header("Content-Type: image/png"); imagepng ($im); } //释放空间 imagedestroy($im); imagedestroy($goodImg); imagedestroy($codeImg); } /** * 从图片文件创建Image资源 * @param $file 图片文件,支持url * @return bool|resource 成功返回图片image资源,失败返回false */ function createImageFromFile($file){ if(preg_match('/http(s)?:\/\//',$file)){ $fileSuffix = getNetworkImgType($file); }else{ $fileSuffix = pathinfo($file, PATHINFO_EXTENSION); } if(!$fileSuffix) return false; switch ($fileSuffix){ case 'jpeg': $theImage = @imagecreatefromjpeg($file); break; case 'jpg': $theImage = @imagecreatefromjpeg($file); break; case 'png': $theImage = @imagecreatefrompng($file); break; case 'gif': $theImage = @imagecreatefromgif($file); break; default: $theImage = @imagecreatefromstring(file_get_contents($file)); break; } return $theImage; } /** * 获取网络图片类型 * @param $url 网络图片url,支持不带后缀名url * @return bool */ function getNetworkImgType($url){ $ch = curl_init(); //初始化curl curl_setopt($ch, CURLOPT_URL, $url); //设置需要获取的URL curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);//设置超时 curl_setopt($ch, CURLOPT_TIMEOUT, 3); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //支持https curl_exec($ch);//执行curl会话 $http_code = curl_getinfo($ch);//获取curl连接资源句柄信息 curl_close($ch);//关闭资源连接 if ($http_code['http_code'] == 200) { $theImgType = explode('/',$http_code['content_type']); if($theImgType[0] == 'image'){ return $theImgType[1]; }else{ return false; } }else{ return false; } } /** * 分行连续截取字符串 * @param $str 需要截取的字符串,UTF-8 * @param int $row 截取的行数 * @param int $number 每行截取的字数,中文长度 * @param bool $suffix 最后行是否添加‘...’后缀 * @return array 返回数组共$row个元素,下标1到$row */ function cn_row_substr($str,$row = 1,$number = 10,$suffix = true){ $result = array(); for ($r=1;$r<=$row;$r++){ $result[$r] = ''; } $str = trim($str); if(!$str) return $result; $theStrlen = strlen($str); //每行实际字节长度 $oneRowNum = $number * 3; for($r=1;$r<=$row;$r++){ if($r == $row and $theStrlen > $r * $oneRowNum and $suffix){ $result[$r] = mg_cn_substr($str,$oneRowNum-6,($r-1)* $oneRowNum).'...'; }else{ $result[$r] = mg_cn_substr($str,$oneRowNum,($r-1)* $oneRowNum); } if($theStrlen < $r * $oneRowNum) break; } return $result; } /** * 按字节截取utf-8字符串 * 识别汉字全角符号,全角中文3个字节,半角英文1个字节 * @param $str 需要切取的字符串 * @param $len 截取长度[字节] * @param int $start 截取开始位置,默认0 * @return string */ function mg_cn_substr($str,$len,$start = 0){ $q_str = ''; $q_strlen = ($start + $len)>strlen($str) ? strlen($str) : ($start + $len); //如果start不为起始位置,若起始位置为乱码就按照UTF-8编码获取新start if($start and json_encode(substr($str,$start,1)) === false){ for($a=0;$a<3;$a++){ $new_start = $start + $a; $m_str = substr($str,$new_start,3); if(json_encode($m_str) !== false) { $start = $new_start; break; } } } //切取内容 for($i=$start;$i<$q_strlen;$i++){ //ord()函数取得substr()的第一个字符的ASCII码,如果大于0xa0的话则是中文字符 if(ord(substr($str,$i,1))>0xa0){ $q_str .= substr($str,$i,3); $i+=2; }else{ $q_str .= substr($str,$i,1); } } return $q_str; } //使用方法------------------------------------------------- //数据格式,如没有优惠券coupon_price值为0。 $gData = [ 'pic' => 'code_png/nv_img.jpg', 'title' =>'chic韩版工装羽绒棉服女冬中长款2017新款棉袄大毛领收腰棉衣外套', 'price' => 19.8, 'original_price' => 119.8, 'coupon_price' => 100 ]; //直接输出 createSharePng($gData,'code_png/php_code.jpg'); //输出到图片 createSharePng($gData,'code_png/php_code.jpg','share.png');
以上是PHP生成分享图片实例的详细内容。更多信息请关注PHP中文网其他相关文章!

PHP主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。

PHP起源于1994年,由RasmusLerdorf开发,最初用于跟踪网站访问者,逐渐演变为服务器端脚本语言,广泛应用于网页开发。Python由GuidovanRossum于1980年代末开发,1991年首次发布,强调代码可读性和简洁性,适用于科学计算、数据分析等领域。

PHP适合网页开发和快速原型开发,Python适用于数据科学和机器学习。1.PHP用于动态网页开发,语法简单,适合快速开发。2.Python语法简洁,适用于多领域,库生态系统强大。

PHP在现代化进程中仍然重要,因为它支持大量网站和应用,并通过框架适应开发需求。1.PHP7提升了性能并引入了新功能。2.现代框架如Laravel、Symfony和CodeIgniter简化开发,提高代码质量。3.性能优化和最佳实践进一步提升应用效率。

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP类型提示提升代码质量和可读性。1)标量类型提示:自PHP7.0起,允许在函数参数中指定基本数据类型,如int、float等。2)返回类型提示:确保函数返回值类型的一致性。3)联合类型提示:自PHP8.0起,允许在函数参数或返回值中指定多个类型。4)可空类型提示:允许包含null值,处理可能返回空值的函数。

PHP中使用clone关键字创建对象副本,并通过\_\_clone魔法方法定制克隆行为。1.使用clone关键字进行浅拷贝,克隆对象的属性但不克隆对象属性内的对象。2.通过\_\_clone方法可以深拷贝嵌套对象,避免浅拷贝问题。3.注意避免克隆中的循环引用和性能问题,优化克隆操作以提高效率。

PHP适用于Web开发和内容管理系统,Python适合数据科学、机器学习和自动化脚本。1.PHP在构建快速、可扩展的网站和应用程序方面表现出色,常用于WordPress等CMS。2.Python在数据科学和机器学习领域表现卓越,拥有丰富的库如NumPy和TensorFlow。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。