/** * 网络图片转换到本地并转换成base64位 * @param $url * @return string */ public function imgzhuanhuan($url) { //网络图片路径 // $url='https://img.jinse.com/1435941_small.png'; //获取文件后缀 $type = substr($url, strrpos($url, ".")+1); //本地路径 $path=public_path().'/images/'.time().'.png'; //反斜杠替换为/ $path=str_replace('\','/',$path); //网上图片保存到本地 $paths=$this->curl_file_get_contents($url, $path); //转换成base64位 $base64_image=$this->base64EncodeImage($paths); //删除本地图片 @unlink($paths); return $base64_image; } //这里的path是我再本地项目中的临时存储路径:'upload/pictrue/xxx.png' //这个路径是要提前创建的,类似于一个空的模板,然后通过curl把二进制的图片流写进去 //$url是网络图片的地址 public function curl_file_get_contents($url, $path) { $hander = curl_init(); $fp = fopen($path, 'wb'); curl_setopt($hander, CURLOPT_URL, $url); curl_setopt($hander, CURLOPT_FILE, $fp); curl_setopt($hander, CURLOPT_HEADER, 0); curl_setopt($hander, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($hander, CURLOPT_TIMEOUT, 60); curl_exec($hander); curl_close($hander); fclose($fp); return $path; } public function base64EncodeImage ($image_file) { $base64_image = ''; $image_info = getimagesize($image_file); $image_data = fread(fopen($image_file, 'r'), filesize($image_file)); $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data)); return $base64_image; }