微信公众号PHP生成二维码海报的几个小扩展

  •   
  • 3537
  • PHP
  • 0
  • super_dodo
  • 2019/07/03

往微信公众平台生成的二维码中间加入公众号logo、远程下载图片到本地、PHP启用gzip输出、PHP提前输出结果等,示例和方法都如下,请各位自行尝试。

###往微信公众平台生成的二维码中间加入公众号logo
/**
    * 二维码内部新增LOGO
    * @param  [string] $QR 二维码地址 
    * @param  [string] $logo 公众号logo
    * @param  [string] $save_img 存储地址
    * @return 已订阅返回true 没有订阅返回false
*/
function createQRLogo($QR,$logo,$save_img) {
    $errorCorrectionLevel = 'L';//容错级别 
    $matrixPointSize = 6;//生成图片大小 
    $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); 
    //保存图片 
    imagejpeg ($QR,$save_img,90);
    imagedestroy($QR);
    return true;
}

createQRLogo('qrcode.png','logo.jpg','new.jpg');



###远程下载图片到本地

/**
    * 下载远程文件到本地
    * @param [string] $url 文件远程地址
    * @param [string] $file_path 文件本地存储路径
    * @author xu
    * @copyright 2018-11-14
*/
function download($url, $file_path)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $file = curl_exec($ch);
    curl_close($ch);
    $handle = @fopen($file_path, 'a');
    fwrite($handle, $file);
    fclose($handle);
}
$images = [
  'http://thirdwx.qlogo.cn/mmopen/abc.png',
];

foreach ( $images as $url ) {
  download($url,'a.jpg');
}




###PHP启用gzip输出 - 有时候输出的页面非常大会自动分块chunked不如压缩以后传输会更快
###如果页面5m采用gzip的话可以变位1m左右


// 将文本gz压缩后缓存起来输出 - 静态化常用
$str = 'abc';
$gz = gzopen ('tmp.gz','w9' );
gzwrite ($gz,$str);
gzclose ($gz);
header("Content-Encoding: gzip");
header("Vary: Accept-Encoding");
echo file_get_contents('tmp.gz');
die;


// 字符串直接压缩后输出
$str = 'abc';
$str = gzencode($str,9);
header("Content-Encoding: gzip");
header("Vary: Accept-Encoding");
echo $str;






###PHP提前输出结果 - 微信服务器在限定时间内未收到响应会重复发送请求 
###生成图片比较慢的话就要提前输出空字符串避免微信服务器重试

// 提前输出
ob_end_clean();
header("Connection: close");
header("HTTP/1.1 200 OK");
// 如果前端要的是json则添加,默认是返回的html/text
header("Content-Type: application/json;charset=utf-8");
ob_start();
echo 'hello world.';// 防止微信服务器重复请求
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
if (function_exists("fastcgi_finish_request")) { 
    fastcgi_finish_request(); 
}


// 在关闭连接后,继续运行php脚本
ignore_user_abort(true);
set_time_limit(0);

sleep(100);


人生不设限,一切皆有可能,竭尽全力,方有可成。