PHP分享图片的生成方法


Posted in PHP onApril 25, 2018

最近工作需求需要生成分享图片,最初用js的html2canvas截图插件各种问题,后来干脆PHP的PG库在后台生成图片,很愉快的解决了各种问题,我们要实现的效果如下图:

PHP分享图片的生成方法

假设代码中用到的资源文件夹在当前code_png目录下:

php代码:

/** 
 * 分享图片生成 
 * @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 数据库树的遍历方法
Feb 06 PHP
php读取javascript设置的cookies的代码
Apr 12 PHP
兼容firefox,chrome的网页灰度效果
Aug 08 PHP
pdo中使用参数化查询sql
Aug 11 PHP
仿Aspnetpager的一个PHP分页类代码 附源码下载
Oct 08 PHP
PHP中把stdClass Object转array的几个方法
May 08 PHP
php中文验证码实现方法
Jun 18 PHP
php使用escapeshellarg时中文被过滤的解决方法
Jul 10 PHP
JSON两种结构之对象和数组的理解
Jul 19 PHP
Ajax+PHP实现的分类列表框功能示例
Feb 11 PHP
php简单计算权重的方法示例【适合抽奖类应用】
Jun 10 PHP
php优化查询foreach代码实例讲解
Mar 24 PHP
PHP receiveMail实现收邮件功能
Apr 25 #PHP
laravel中短信发送验证码的实现方法
Apr 25 #PHP
PHP设计模式之适配器模式原理与用法分析
Apr 25 #PHP
PHP设计模式之原型设计模式原理与用法分析
Apr 25 #PHP
PHP设计模式之单例模式原理与实现方法分析
Apr 25 #PHP
PHP设计模式之工厂方法设计模式实例分析
Apr 25 #PHP
原生php实现excel文件读写的方法分析
Apr 25 #PHP
You might like
修改php.ini以达到屏蔽错误信息并记录日志
2013/06/16 PHP
浅析php变量作用域的一些问题
2013/08/08 PHP
php图片缩放实现方法
2014/02/20 PHP
访问编码后的中文URL返回404错误的解决方法
2014/08/20 PHP
php获取ajax的headers方法与内容实例
2017/12/27 PHP
PHP简单实现解析xml为数组的方法
2018/05/02 PHP
使用jquery与图片美化checkbox和radio控件的代码(打包下载)
2010/11/11 Javascript
javascript中xml操作实现代码
2011/11/21 Javascript
两种方法基于jQuery实现IE浏览器兼容placeholder效果
2014/10/14 Javascript
为什么Node.js会这么火呢?Node.js流行的原因
2014/12/01 Javascript
JavaScript数组各种常见用法实例分析
2015/08/04 Javascript
javascript:void(0)点击登录没反应怎么解决
2015/11/13 Javascript
BootStrap glyphicon图标无法显示的解决方法
2016/09/06 Javascript
jQuery.ajax实现根据不同的Content-Type做出不同的响应
2016/11/03 Javascript
基于JavaScript实现熔岩灯效果导航菜单
2017/01/04 Javascript
js获取浏览器和屏幕的各种宽度高度
2017/02/22 Javascript
微信小程序 navbar实例详解
2017/05/11 Javascript
laydate日历控件使用方法详解
2017/11/20 Javascript
vue.js轮播图组件使用方法详解
2018/07/03 Javascript
关于vue-cli 3配置打包优化要点(推荐)
2019/04/22 Javascript
python中使用smtplib和email模块发送邮件实例
2014/04/22 Python
python 将print输出的内容保存到txt文件中
2018/07/17 Python
用Python读取几十万行文本数据
2018/12/24 Python
只需7行Python代码玩转微信自动聊天
2019/01/27 Python
详解如何设置Python环境变量?
2019/05/13 Python
使用python将多个excel文件合并到同一个文件的方法
2019/07/09 Python
在OpenCV里实现条码区域识别的方法示例
2019/12/04 Python
在Windows上安装和配置 Jupyter Lab 作为桌面级应用程序教程
2020/04/22 Python
tensorflow pb to tflite 精度下降详解
2020/05/25 Python
最耐用行李箱,一箱永流传:Briggs & Riley(全球终身保修)
2017/12/07 全球购物
全球500多个机场的接送服务:Suntransfers
2019/06/03 全球购物
关于读书的演讲稿500字
2014/08/27 职场文书
党小组推荐意见
2015/06/02 职场文书
Python爬虫爬取全球疫情数据并存储到mysql数据库的步骤
2021/03/29 Python
Golang生成Excel文档的方法步骤
2021/06/09 Golang
python APScheduler执行定时任务介绍
2022/04/19 Python