Table of Contents
Articles you may be interested in:
Home Backend Development PHP Tutorial PHP sharing image generation method php skills

PHP sharing image generation method php skills

Jun 26, 2018 pm 05:13 PM
php

This article mainly introduces the method of generating shared pictures in PHP, which is similar to the Taobao baby sharing picture function and has a certain reference value. Interested friends can refer to

Recent work requirements require generating sharing For pictures, I initially used js's html2canvas screenshot plug-in to solve various problems. Later, I simply used PHP's PG library to generate pictures in the background. I happily solved various problems. The effect we want to achieve is as follows:

Assume that the resource folder used in the code is in the current code_png directory:

php code:

/** 
 * 分享图片生成 
 * @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;);
Copy after login

above That’s the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support the php Chinese website.

Articles you may be interested in:

Laravel 5.4 vue vux element environment matching process introduction PHP example

php-fpm Add service service example php instance

php-fpm service startup script method php instance

The above is the detailed content of PHP sharing image generation method php skills. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles