远程图片转化为base64

远程图片转化为base64

远程图片转化为base64

    <?php
/* *
* 第一种方法
* 远程图片转化为base64,只支持http(推荐使用)
* */
public static function imgUrl_to_base64($url,$auto_http = false){
/* $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',);*/
if(strpos($url,'https://') !== false && $auto_http == true){
//是否自动转为http
$url = str_replace('https://','http://',$url);
}
$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);
$imgBase64Code = '';
if($code == 200){
$imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
} return $imgBase64Code;
} /* *
* 第二种方法
* 远程图片转化为base64,支持https,http(比较消耗服务器资源)
* */
function imgUrl_base64($url){
$url='https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJm4xPKAf4u6TAQ6AGmXEmBh4yfyFcfZTOQoRzumzBEvIPaaRJXAB8Rlia1iaugJWRsdqzBhu3BTtkw/0';
$img_file = file_get_contents($url); $img_content= "data:image/jpeg;base64," .base64_encode($img_file);
return $img_content;
} ?>
05-11 09:14