PHP下载微信头像 微信活动海报
最近搞一个微信分享吸粉的活动,需要生成用户推广海报,使用TP的图像处理类可轻易添加昵称、图片、二维码等水印信息。但在生成此海报时,由于下载微信头像到本地/服务器用时太长,导致海报生成时间过长问题。
解决方法
使用curl压缩下载图片,加速图片下载速度,实现海报生成速度由8s
左右到1s
的提升。
public function download($url, $uid)
{
$path = Env::get('root_path').'public/avatar/'.date('Ym').'/';
is_dir($path) ?: mkdir($path, 0777, true);
$header = array('User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0', 'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Accept-Encoding: gzip, deflate');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
$data = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($code == 200) {
$imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
}
$img_content=$imgBase64Code;//图片内容
//echo $img_content;exit;
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)){
$type = $result[2];
$new_file = $path.$uid.'.jpg';
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))){
// echo '新文件保存成功:', $new_file;
}
}
}