搜尋
首頁後端開發php教程PHP做出分享圖片功能

PHP做出分享圖片功能

May 16, 2018 pm 01:55 PM
php功能圖片

這次帶給大家PHP做出分享圖片功能,PHP做出分享圖片功能的注意事項有哪些,以下就是實戰案例,一起來看一下。

最近工作需求需要產生分享圖片,最初用js的html2canvas截圖外掛各種問題,後來乾脆PHP的PG庫在後台產生圖片,很愉快的解決了各種問題,我們要實現的效果如下圖:

假設程式碼中用到的資源資料夾在目前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] = &#39;&#39;; 
  } 
 
  $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).&#39;...&#39;; 
    }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 = &#39;&#39;; 
  $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 = [ 
  &#39;pic&#39; => &#39;code_png/nv_img.jpg&#39;, 
  &#39;title&#39; =>&#39;chic韩版工装羽绒棉服女冬中长款2017新款棉袄大毛领收腰棉衣外套&#39;, 
  &#39;price&#39; => 19.8, 
  &#39;original_price&#39; => 119.8, 
  &#39;coupon_price&#39; => 100 
]; 
//直接输出 
createSharePng($gData,&#39;code_png/php_code.jpg&#39;); 
//输出到图片 
createSharePng($gData,&#39;code_png/php_code.jpg&#39;,&#39;share.png&#39;);

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

PHP取得檔案副檔名方式總結

#怎麼讓360搜尋引擎收錄php改寫方法

以上是PHP做出分享圖片功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
可以在PHP會話中存儲哪些數據?可以在PHP會話中存儲哪些數據?May 02, 2025 am 12:17 AM

phpsessionscanStorestrings,數字,數組和原始物。

您如何開始PHP會話?您如何開始PHP會話?May 02, 2025 am 12:16 AM

tostartaphpsession,usesesses_start()attheScript'Sbeginning.1)placeitbeforeanyOutputtosetThesessionCookie.2)useSessionsforuserDatalikeloginstatusorshoppingcarts.3)regenerateSessiveIdStopreventFentfixationAttacks.s.4)考慮使用AttActAcks.s.s.4)

什麼是會話再生,如何提高安全性?什麼是會話再生,如何提高安全性?May 02, 2025 am 12:15 AM

會話再生是指在用戶進行敏感操作時生成新會話ID並使舊ID失效,以防會話固定攻擊。實現步驟包括:1.檢測敏感操作,2.生成新會話ID,3.銷毀舊會話ID,4.更新用戶端會話信息。

使用PHP會話時有哪些性能考慮?使用PHP會話時有哪些性能考慮?May 02, 2025 am 12:11 AM

PHP会话对应用性能有显著影响。优化方法包括:1.使用数据库存储会话数据,提升响应速度;2.减少会话数据使用,只存储必要信息;3.采用非阻塞会话处理器,提高并发能力;4.调整会话过期时间,平衡用户体验和服务器负担;5.使用持久会话,减少数据读写次数。

PHP會話與Cookie有何不同?PHP會話與Cookie有何不同?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

PHP如何識別用戶的會話?PHP如何識別用戶的會話?May 01, 2025 am 12:23 AM

phpIdentifiesauser'ssessionSessionSessionCookiesAndSessionId.1)whiwsession_start()被稱為,phpgeneratesainiquesesesessionIdStoredInacookInAcookInAcienamedInAcienamedphpsessIdontheuser'sbrowser'sbrowser.2)thisIdallowSphptpptpptpptpptpptpptpptoretoreteretrieetrieetrieetrieetrieetrieetreetrieetrieetrieetrieetremthafromtheserver。

確保PHP會議的一些最佳實踐是什麼?確保PHP會議的一些最佳實踐是什麼?May 01, 2025 am 12:22 AM

PHP會話的安全可以通過以下措施實現:1.使用session_regenerate_id()在用戶登錄或重要操作時重新生成會話ID。 2.通過HTTPS協議加密傳輸會話ID。 3.使用session_save_path()指定安全目錄存儲會話數據,並正確設置權限。

PHP會話文件默認存儲在哪裡?PHP會話文件默認存儲在哪裡?May 01, 2025 am 12:15 AM

phpsessionFilesArestoredIntheDirectorySpecifiedBysession.save_path,通常是/tmponunix-likesystemsorc:\ windows \ windows \ temponwindows.tocustomizethis:tocustomizEthis:1)useession_save_save_save_path_path()

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境