PHP Generate share Picture instance

Source: Internet
Author: User
Recently work needs to generate share pictures, initially with JS Html2canvas plug-in various problems, and then simply PHP PG Library in the background to generate pictures, very happy to solve the various problems, we want to achieve the effect such as:


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

/** * Share image generation * @param $gData product data, array * @param $codeName QR code image * @param $fileName string to save the file name, default NULL to enter the image directly */function CR    Eatesharepng ($gData, $codeName, $fileName = ") {//create canvas $im = Imagecreatetruecolor (618, 1000);    Fill canvas background Color $color = imagecolorallocate ($im, 255, 255, 255);    Imagefill ($im, 0, 0, $color);    Font file $font _file = "Code_png/msyh.ttf";    $font _file_bold = "Code_png/msyh_bold.ttf";    Sets the color of the font $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, 0, 0, _w, $l, $l _h); Warm hints Imagettftext ($im, 14,0, $font, $font _color_1, _fIle, ' warm hint: like long press image identification QR code can go to buy ');    Product Picture 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);    QR code list ($code _w, $code _h) = getimagesize ($codeName);    $CODEIMG = Createimagefromfile ($codeName);    Imagecopyresized ($im, $CODEIMG, 820, _w, 0, 0, $code, $code _h);    Product Description $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, "coupon ¥");    Imagettftext ($im, 28,0, 935, $font _color_red, $font _file_bold, $gData ["Price"]);    Imagettftext ($im, 14,0, 8,970, $font _color_3, $font _file, "pay ¥". $gData ["Original_price"]);        Coupon if ($gData [' Coupon_price ']) {imagerectangle ($im, 950, 975, $font _color_3); ImagefilledrectAngle ($im, 126, 951, 159, 974, $fang _bg_color);        Imagettftext ($im, 14,0, 135,970, $font _color_3, $font _file, "coupons");        $coupon _price = Strval ($gData [' coupon_price ']);        Imagerectangle ($im, 950, 198 + (strlen ($coupon _price) *), 975, $font _color_3); Imagettftext ($im, 14,0, 170,970, $font _color_3, $font _file, $coupon _price. "    Yuan ");    }//Output picture if ($fileName) {imagepng ($im, $fileName);        }else{Header ("Content-type:image/png");    Imagepng ($im);    }//Free space Imagedestroy ($IM);    Imagedestroy ($GOODIMG); Imagedestroy ($CODEIMG);} /** * Create image resource from picture file * @param $file picture file, support URL * @return Bool|resource successfully returned picture image resource, failed to return false */function CREATEIMAGEFR Omfile ($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;} /** * Get network Picture type * @param $url network image URL, support without suffix name URL * @return bool */function getnetworkimgtype ($url) {$ch = Curl_init (); Initialize Curl curl_setopt ($ch, Curlopt_url, $url);    Set the URL to get curl_setopt ($ch, curlopt_nobody, 1);    curl_setopt ($ch, Curlopt_connecttimeout, 3);//Set timeout curl_setopt ($ch, Curlopt_timeout, 3); curl_setopt ($ch, Curlopt_ssl_verifypeer, false); Support HTTPS curl_exec ($ch),//Perform curl session $http _code = Curl_getinfo ($ch),//Get Curl Connection resource handle information curl_close ($ch);//close Resource connection I F ($http _code[' http_code ' = =) {$theImgType = expLode ('/', $http _code[' Content_Type ');        if ($theImgType [0] = = ' image ') {return $theImgType [1];        }else{return false;    }}else{return false;  }}/** * Branch Intercept String * @param $str the string to intercept, UTF-8 * @param int $row The number of rows intercepted * @param int $number The length of words intercepted per line, Chinese * @param bool $suffix the last line to add ' ... ' suffix * @return array returns an array of $row elements, subscript 1 to $row */function cn_row_substr ($str, $row = 1, $number = ten, $suf    Fix = True) {$result = array ();    for ($r =1; $r <= $row; $r + +) {$result [$r] = ';    } $str = Trim ($STR);    if (! $str) return $result;    $theStrlen = strlen ($STR);    Actual byte length per line $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;} /** * intercept utf-8 strings by byte * Recognize Chinese full-width symbols, full-width Chinese 3 bytes, half-width English 1 bytes * @param $str The string to be truncated * @param $len intercept length [bytes] * @param int $start intercept    Start position, default 0 * @return string */function mg_cn_substr ($str, $len, $start = 0) {$q _str = '; $q _strlen = ($start + $len) >strlen ($STR)?    Strlen ($STR): ($start + $len); If start is not the starting position, if the starting position is garbled, get the new start if ($start and Json_encode (substr ($str, $start, 1)) = = = False) {for ($a =0) in the UTF-8 encoding.            , $a <3; $a + +) {$new _start = $start + $a;            $m _str = substr ($str, $new _start,3);                if (Json_encode ($m _str)!== false) {$start = $new _start;            Break         }}}//Cut content for ($i = $start; $i < $q _strlen; $i + +) {//ord () function gets the ASCII code for the first character of substr (), or Chinese characters if greater than 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;} How to use-------------------------------------------------//Data format, if no coupon Coupon_price value is 0. $gData = [' pic ' = ' code_png/nv_img.jpg ', ' title ' and ' Chic '-han version frock down cotton dress female winter midi 2017 new style cotton-padded wool collar waist-coat jacket ', ' price ' = 19 .8, ' Original_price ' + 119.8, ' coupon_price ' = 100];//Direct output createsharepng ($gData, ' code_png/php_code.jpg ');//Loss Out to the picture createsharepng ($gData, ' code_png/php_code.jpg ', ' share.png ');

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.