方法一(推荐):
1function download_remote_pic($url){ 2 $header = [ 3 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0', 4 'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 5 'Accept-Encoding: gzip, deflate', 6 ]; 7 $curl = curl_init(); 8 curl_setopt($curl, CURLOPT_URL, $url); 9 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 10 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); 11 curl_setopt($curl, CURLOPT_ENCODING, 'gzip'); 12 curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 13 $data = curl_exec($curl); 14 $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); 15 curl_close($curl); 16 if ($code == 200) {//把URL格式的图片转成base64_encode格式的! 17 $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data); 18 } 19 $img_content=$imgBase64Code;//图片内容 20 //echo $img_content;exit; 21 if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) { 22 $type = $result[2];//得到图片类型png?jpg?gif? 23 $new_file = "./".time().rand(1,10000).".{$type}"; 24 if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) { 25 return $new_file; 26 } 27 } 28} 29$new_file = download_remote_pic('http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLlib3rTHIt2n0nrYFibmOc69IWwLABiaEMicfg0iahGUhP93jYicNZ5MWL9yYlHvibdlG36xWHuPs0p3ibPQ/132'); 30 31echo $new_file;
方法二(慢,消耗服务器)
1$url='http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLlib3rTHIt2n0nrYFibmOc69IWwLABiaEMicfg0iahGUhP93jYicNZ5MWL9yYlHvibdlG36xWHuPs0p3ibPQ/132'; 2$new_file = "./".time().rand(1,10000).".png"; //图片类型getimagesize($url)可以但是因为是远程图片太慢了 3file_put_contents($new_file, file_get_contents($url)); 4echo ($new_file);
图片转base64
1function base64_encode_image($file){ 2 $type=getimagesize($file);//取得图片的大小,类型等 3 $fp=fopen($file,"r")or die("Can't open file"); 4 5 $file_content=chunk_split(base64_encode(fread($fp,filesize($file))));//base64编码 6 switch($type[2]){//判读图片类型 7 case 1:$img_type="gif";break; 8 case 2:$img_type="jpg";break; 9 case 3:$img_type="png";break; 10 } 11 $img='data:image/'.$img_type.';base64,'.$file_content;//合成图片的base64编码 12 fclose($fp); 13 return $img; 14}