PHP远程下载图片,微信头像存到本地,本地图片转base64

方法一(推荐):

function download_remote_pic($url){
    $header = [
        '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) {//把URL格式的图片转成base64_encode格式的!      
       $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];//得到图片类型png?jpg?gif?   
        $new_file = "./".time().rand(1,10000).".{$type}";   
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) {  
            return $new_file; 
        }
    } 
}
$new_file = download_remote_pic('http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLlib3rTHIt2n0nrYFibmOc69IWwLABiaEMicfg0iahGUhP93jYicNZ5MWL9yYlHvibdlG36xWHuPs0p3ibPQ/132');

echo $new_file;

方法二(慢,消耗服务器)

$url='http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLlib3rTHIt2n0nrYFibmOc69IWwLABiaEMicfg0iahGUhP93jYicNZ5MWL9yYlHvibdlG36xWHuPs0p3ibPQ/132';  
$new_file = "./".time().rand(1,10000).".png"; //图片类型getimagesize($url)可以但是因为是远程图片太慢了
file_put_contents($new_file, file_get_contents($url));
echo ($new_file);

图片转base64

function base64_encode_image($file){
    $type=getimagesize($file);//取得图片的大小,类型等  
    $fp=fopen($file,"r")or die("Can't open file");  

    $file_content=chunk_split(base64_encode(fread($fp,filesize($file))));//base64编码  
    switch($type[2]){//判读图片类型  
        case 1:$img_type="gif";break;  
        case 2:$img_type="jpg";break;  
        case 3:$img_type="png";break;  
    }  
    $img='data:image/'.$img_type.';base64,'.$file_content;//合成图片的base64编码  
    fclose($fp);  
    return $img;
}

猜你喜欢

转载自www.cnblogs.com/wangzhaobo/p/9174530.html