如何用 PHP 给你的网站添加分享二维码海报功能?

你想不想给你的网站或者博客制作一张带有网站信息+二维码+logo的宣传海报功能?
分享海报可以是让文章更具有可分享性,同时也可以为个人品牌、商务推广等提供便利。PHP 是一门强大的编程语言,使用它可以轻松制作分享海报。本文将介绍如何使用 PHP 制作分享海报。

这里我们需要用到PHP二维码生成库phpqrcode,附上下载地址:https://sourceforge.net/projects/phpqrcode/,下载后是个ZIP文件,解压后只需用到phpqrcode.php。

phpqrcode是一个常用的PHP二维码生成库,它可以轻松地生成二维码图像。 在上述代码示例中,我们首先包含了phpqrcode库,然后使用QRcode类的png()方法生成一个PNG格式的二维码图像,并将其输出到浏览器。 您可以根据需要调整代码,以生成和输出您所需的二维码图像。

下面进入正题,首先我们需要引入 phpqrcode.php 文件:

include 'phpqrcode.php'; // 引入phpqrcode二维码生成类库文件

然后,我们定义一些变量和数组,分别代表二维码的 url 地址、logo 图片、已生成的原始二维码图等:

$value = "https://www.dujup.com"; // 二维码url地址
$logo = 'logo.png';               // logo
$QR = 'qrcode.png';               // 已经生成的原始二维码图
$data = [
    'background' => 'background.jpg',  // 主背景图 
'bg' => 'bg.jpg', // 文字背景图 'title' => 'YUDAY分享网', // 主标题 'subtitle' => '专注科技分享', // 副标题 'cat' => "PHP", // 文章分类 'introduce' => "制作二维码分享海报...", // 简介 'EssayName' => '《php制作分享海报》', // 文章名 'qrcode' => 'qrcode.png', // 二维码图片 'logo' => 'w-logo-blue.png', ];

接下来,我们使用 QRcode::png() 函数,生成二维码图像。该函数包括五个参数,分别是:二维码内容、二维码保存路径、容错级别、点的大小、外边框的宽度。

$errorCorrectionLevel = 'L'; // 容错级别
$matrixPointSize = 6;
QRcode::png($value, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);

然后,我们将 logo 图片嵌入到二维码中心,以达到美观的效果。使用 imagecreatefromstring() 函数读取图像文件,然后使用 imagecopyresampled() 函数将 logo 图片重新组合并调整大小,将其嵌入二维码中心。

if ($logo !== FALSE) {
    $QR = imagecreatefromstring(file_get_contents($QR));
    $logo = imagecreatefromstring(file_get_contents($logo));
    $QR_width = imagesx($QR); // 二维码图片宽度
    $QR_height = imagesy($QR); // 二维码图片高度
    $logo_width = imagesx($logo); // logo图片宽度
    $logo_height = imagesy($logo); // logo图片高度
    $logo_qr_width = $QR_width / 5;
    $scale = $logo_width/$logo_qr_width;
    $logo_qr_height = $logo_height/$scale;
    $from_width = ($QR_width - $logo_qr_width) / 2;
	//重新组合图片并调整大小
    imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
        $logo_qr_height, $logo_width, $logo_height);
}

然后是文字部分,这里可以根据需要设置,如注明版权之类的:

imagettftext($im, 14, 0, 40, 1215, $font_color_3, $font_file_bold, '版权所有');
imagettftext($im, 14, 0, 148, 1215, $font_color_5, $font_file_bold, 'YUDAY');
imagettftext($im, 14, 0, 208, 1215, $font_color_3, $font_file_bold, ',严禁');
imagettftext($im, 14, 0, 40, 1240, $font_color_3, $font_file_bold, '抄袭、复制、转载本站');
imagettftext($im, 14, 0, 40, 1265, $font_color_3, $font_file_bold, '所有内容。');
imagettftext($im, 14, 0, 40, 1290, $font_color_3, $font_file_bold, '如需转载,请在转载时注');
imagettftext($im, 14, 0, 40, 1315, $font_color_3, $font_file_bold, '明出处,谢谢合作!');

输出图片并释放空间:

	    if($fileName){
	        imagepng ($im,$fileName);
	    }else{
	    	header("Content-type:text/html;charset=utf-8");
	        Header("Content-Type: image/png");
	        imagepng ($im);
	    }
	 
	    //释放空间	
	    imagedestroy($QR); 
	    imagedestroy($im);
	    imagedestroy($goodImg);
	    imagedestroy($codeImg);

根据图片地址创建图片函数:

 function createImageFromFile($file){
    $info = @getimagesize($file);
    if(!$info){
        return false;
    }
    switch ($info[2]) {
        case 1:
            $im = imagecreatefromgif($file);
            break;
        case 2:
            $im = imagecreatefromjpeg($file);
            break;
        case 3:
            $im = imagecreatefrompng($file);
            break;
        default:
            $im = false;
            break;
    }
    return $im;
}


下面是完整代码:

include 'phpqrcode.php';  //引入phpqrcode二维码生成类库文件
$value =  "YOU URL";      //二维码url地址
$logo = 'logo.png';  		
$QR = 'qrcode.png';//已经生成的原始二维码图
	 	$data = [
	 	    'background' => 'background.jpg',//主背景图 
'bg' => 'bg.jpg', //文字背景图 'title' =>'网站名', //主标题 'subtitle' =>'副标题', //副标题 'cat' => "分类", //文章分类 'introduce' =>"这里是文章的简介...", //简介 'EssayName' => '《文章标题》', //文章名 'qrcode' => 'qrcode.png', //二维码图片 'logo' => 'logo.png', //logo图片 ]; $errorCorrectionLevel = 'L';//容错级别 $matrixPointSize = 6; QRcode::png($value, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2); if ($logo !== FALSE) { $QR = imagecreatefromstring(file_get_contents($QR)); $logo = imagecreatefromstring(file_get_contents($logo)); $QR_width = imagesx($QR);//二维码图片宽度 $QR_height = imagesy($QR);//二维码图片高度 $logo_width = imagesx($logo);//logo图片宽度 $logo_height = imagesy($logo);//logo图片高度 $logo_qr_width = $QR_width / 5; $scale = $logo_width/$logo_qr_width; $logo_qr_height = $logo_height/$scale; $from_width = ($QR_width - $logo_qr_width) / 2; //重新组合图片并调整大小 imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height); } //保存再输出图片 imagepng($QR, 'qrcode.png'); createSharePng($data); // 分享图片生成 function createSharePng($data,$fileName = ''){ //创建画布 $im = imagecreatetruecolor(750, 1334); //填充画布背景色 $color = imagecolorallocate($im, 255, 255, 255); imagefill($im, 0, 0, $color); $font_file = "./msyh.ttf"; //字体文件 $font_file_bold = "./msyhbd.ttf"; $font_file= realpath($font_file); //realpath函数获取绝对路径 $font_file_bold= realpath($font_file_bold); //设定字体的颜色 $font_color_1 = ImageColorAllocate ($im, 255, 168, 98); $font_color_2 = ImageColorAllocate ($im, 51, 51, 51); $font_color_3 = ImageColorAllocate ($im, 153, 153, 153); $font_color_4 = ImageColorAllocate ($im, 255, 255, 255); $font_color_5 = ImageColorAllocate ($im, 255, 98, 98); $font_color_6 = ImageColorAllocate ($im, 83, 04, 21); // 海报背景图 list($g_w,$g_h) = getimagesize($data['background']); $goodImg = createImageFromFile($data['background']); imagecopyresized($im, $goodImg, 0, 0, 0, 0, 750, 1334, $g_w, $g_h); // logo list($l_w,$l_h) = getimagesize($data['logo']); $logoImg = imagecreatefrompng($data['logo']); imagecopyresized($im, $logoImg, 30, 100, 0, 0, 100, 100, $l_w, $l_h); //文字背景底图 list($l_w,$l_h) = getimagesize($data['bg']); $logoImg = createImageFromFile($data['bg']); imagecopyresized($im, $logoImg, 30, 950, 0, 0, 690, 280, $l_w, $l_h); //二维码 list($code_w,$code_h) = getimagesize($data['qrcode']); $codeImg = createImageFromFile($data['qrcode']); imagecopyresized($im, $codeImg, 60, 980, 0, 0, 180, 180, $code_w, $code_h); //文字 $fontBox = imagettfbbox(50, 0, $font_file, $data['title']); imagettftext($im, 50,0, ceil((750 - $fontBox[2]) / 2), 100, $font_color_4 ,$font_file_bold, $data['title']); imagettftext($im, 50,0, ceil((750 - $fontBox[2]) / 2)-50, 100, $font_color_4 ,$font_file, '-'); imagettftext($im, 50,0, ceil((750 - $fontBox[2]) / 2)+$fontBox[2]+20, 100, $font_color_4 ,$font_file, '-'); $fontBox = imagettfbbox(46, 0, $font_file, $data['subtitle']); imagettftext($im, 46,0, ceil((750 - $fontBox[2]) / 2), 200, $font_color_5 ,$font_file, $data['subtitle']); imagettftext($im, 26,0, 281, 1056, $font_color_2 ,$font_file, $data["EssayName"]); imagettftext($im, 22,0, 281, 1119, $font_color_2 ,$font_file, '文章分类:'.$data["cat"]); imagettftext($im, 22,0, 281, 1168, $font_color_2 ,$font_file, "文章简介:"); imagettftext($im, 22,0, 419,1168, $font_color_2 ,$font_file, $data["introduce"]); imagettftext($im, 22,0, 30,1272, $font_color_4 ,$font_file, "长按保存图片"); imagettftext($im, 18,0, 30,1310, $font_color_4 ,$font_file, "创建日期:".date("Y-m-d h:i").""); //输出图片 if($fileName){ imagepng ($im,$fileName); }else{ header("Content-type:text/html;charset=utf-8"); Header("Content-Type: image/png"); imagepng ($im); } //释放空间 imagedestroy($QR); imagedestroy($im); imagedestroy($goodImg); imagedestroy($codeImg); } function createImageFromFile($file){ if(preg_match('/http(s)?:\/\//',$file)){ $fileSuffix = getNetworkImgType($file); }else{ $file_info = getimagesize($file); $fileSuffix = $file_info[2]; } if(!$fileSuffix) return false; switch ($fileSuffix){ case '2': $theImage = imagecreatefromjpeg($file); break; case '3': $theImage = @imagecreatefrompng($file); break; case '1': $theImage = @imagecreatefromgif($file); break; default: $theImage = @imagecreatefromstring(file_get_contents($file)); break; } return $theImage; } function getNetworkImgType($url){ $ch = curl_init(); //初始化curl curl_setopt($ch, CURLOPT_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); curl_exec($ch); $http_code = curl_getinfo($ch); 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; } } 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; } function mg_cn_substr($str,$len,$start = 0){ $q_str = ''; $q_strlen = ($start + $len)>strlen($str) ? strlen($str) : ($start + $len); if($start and json_encode(substr($str,$start,1)) === false){ for($a=0;$a<3 a="" break="" false="" for="" i="" if="" json_encode="" m_str="" new_start="$start" ord="" start="$new_start;" str="" substr="">0xa0){ $q_str .= substr($str,$i,3); $i+=2; }else{ $q_str .= substr($str,$i,1); } } return $q_str; }

效果图:



使用方法:
将上面代码保存为如:posters.php,然后将phpqrcode.php、logo.png、background.png(背景图片)、文字背景图和字体文件(换成自己的字体文件,不需要可以注释掉)并放在同一目录中。最后,运行这个posters.php文件即可生成海报。

代码中的$data数组定义了海报的各种属性,包括背景图、主标题、副标题、分类、简介、文章名、二维码图片和Logo图片。如果需要更改这些属性,可以通过修改$data数组中的相应值来实现。

代码中使用了phpqrcode类库来生成二维码,可以通过调整容错级别和点阵大小来控制生成的二维码的大小和清晰度。如果您不需要生成二维码,可以将生成二维码的代码段注释掉。

扩展:
以上PHP代码因为演示所有格式写死,你可以使用 $_GET[] 或者 $_POST[]接受参数动态合成海报内的数据。调用时只需要引入posters.php文件然后传入参数,如:posters.php?title=xxx&value=xxx这样方便每次调用时生成对应所需的数据。

演示地址:http://img.dujup.com/bill/