获取远程图片

阅读更多
function put_file_from_url_content($url, $saveName, $path) {
    // 设置运行时间为无限制
    set_time_limit ( 0 );
    $url = trim ( $url );
    $curl = curl_init ();
    // 设置你需要抓取的URL
    curl_setopt ( $curl, CURLOPT_URL, $url );
    // 设置header
    curl_setopt ( $curl, CURLOPT_HEADER, 0 );
    // 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上。
    curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
    // 运行cURL,请求网页
    $file = curl_exec ( $curl );
    // 关闭URL请求
    curl_close ( $curl );
    // 将文件写入获得的数据
    $filename = $path . $saveName;
    $write = @fopen ( $filename, "w" );
    if ($write == false) {
        return false;
    }
    if (fwrite ( $write, $file ) == false) {
        return false;
    }
    if (fclose ( $write ) == false) {
        return false;
    }
    return $filename;
}
//获取远程图片
function GrabImage($url,$thumbDir) {
	$images_types = array(
			'image/png' => 'png',
			'image/jpeg' => 'jpg',
			'image/bmp' => 'bmp',
			'image/gif' => 'gif',
		) ;
	if($url=="")	return false;
	$suffix = strrchr(strrchr($url,"/"),".");
	$filename	=	md5($url).$suffix;
	$filepath = put_file_from_url_content($url,$filename,$thumbDir);
	if ($filepath){
		if (!$suffix){
			$image_info = getimagesize($filepath);
	        $ext = $images_types[$image_info['mime']] ? $images_types[$image_info['mime']] : 'jpg';
	        $new_filepath = $filepath.".".$ext;
	        if (rename($filepath,$new_filepath)){
	        	$filepath = $new_filepath;
	        }
		}
		return $filepath;
	}
	$img		=	file_get_contents($url);
	if(!$img){
		return false;
	}
	$filepath	=	$thumbDir.$filename;
	$result		=	file_put_contents($filepath,$img);
	if($result){
		if (!$suffix){
			$image_info = getimagesize($filepath);
	        $ext = $images_types[$image_info['mime']] ? $images_types[$image_info['mime']] : 'jpg';
	        $new_headimgurl = $filepath.".".$ext;
			if (rename($filepath,$new_filepath)){
	        	$filepath = $new_filepath;
	        }
		}
		return $filepath;
	}else{
		return false;
	}
}

 

  • thumb.zip (7 KB)
  • 下载次数: 0

你可能感兴趣的:(远程图片,缩略图)