读取远程图片的二进制流

时间:2022-11-12 23:56:08

获取图片的二进制流方法很多,file_get_contents,fread,readfile,curl等

1、curl

function httpDownload($url){  
    if(empty($url)){  
        return false;  
    }  
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_TIMEOUT, 2);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$r = curl_exec($ch);
	curl_close($ch);
	return $r;
}

$url为图片地址,返回值$r就是所读取的图片的二进制流

2、readfile:函数读取文件,并把它写入输出缓冲

function httpDownload($url){  
    if(empty($url)){  
        return false;  
    }  
	ob_start();
	$contents = @readfile($url);
	$img = ob_get_contents(); 
	ob_end_clean();
	return $img;
}


3、file_get_contents

function httpDownload($url){  
    if(empty($url)){  
        return false;  
    }  
	$img = file_get_contents($url); 
	return $img;
}

4、fread(filesize无法获取远程文件的大小)

function httpDownload($url){  
    if(empty($url)){  
        return false;  
    }  
	$file = fopen($url,"rb");  //rb是以二进制流的模式打开
	fread($file,filesize($url));
	fclose($file);
}