PHP下載遠程圖片並保存到本地方法

/*
     * 上傳網絡圖片
     */
    function GrabImage($url,$filename="") {
		if($url=="") return false;
		
		if($filename=="") {
			$ext=strrchr($url,".");
			if($ext!=".jpeg" && $ext!=".jpg" && $ext!=".png") return false; 
			preg_match('/\/([^\/]+\.[a-z]{3,4})$/i',$url,$matches);
			$image_name = strToLower($matches[1]);
			$filename='data/runtime/images/'.$image_name;
		}else{
			$image_name = $filename;
			$filename='data/runtime/images/'.$filename;
		}
//方法一
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $file_content = curl_exec($ch);
        curl_close($ch);
        $downloaded_file = fopen($filename, 'w');
        fwrite($downloaded_file, $file_content);
        fclose($downloaded_file);
        return $image_name;

//方法二        
//        $src_im = imagecreatefromjpeg($url);
//        $srcW = ImageSX($src_im); //得到圖像的寬
//        $srcH = ImageSY($src_im); //得到圖像的高
//        $dst_im = ImageCreateTrueColor($srcW,$srcH); //建立新的圖像對象
//        imagecopy($dst_im, $src_im, 0, 0, 0, 0, $srcW, $srcH);
//        imagejpeg($dst_im, $filename); //建立縮略圖文件
 //       return $image_name;

//方法三
//        ob_start();
//        readfile($url);
//        $img = ob_get_contents();
//        ob_end_clean();
//        $size = strlen($img);
//       $fp2=@fopen($filename, "a");
//       fwrite($fp2,$img);
//        fclose($fp2);
//        return $image_name;
	}

ps: http://www.jb51.net/article/78455.htm http://www.cnblogs.com/mengxiaotian/p/5051579.html http://blog.csdn.net/iefreer/article/details/46930239html

相關文章
相關標籤/搜索