1. 程式人生 > >網路圖片轉換到本地並轉換成base64位

網路圖片轉換到本地並轉換成base64位

/**
     * 網路圖片轉換到本地並轉換成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; }