header("Content-type: image/pjpeg");
echo file_get_contents("./201404/1.jpg");
?>
//下载任何格式的文件用:header("Content-type: application/octet-stream");
//顺便给你一个封装好的方法,你只要在需要的地方调用它就好了
function download($file_url,$new_name=''){
if(!isset($file_url)||trim($file_url)==''){
return '500';
}
if(!file_exists($file_url)){ //检查文件是否存在
return '404';
}
$file_name=basename($file_url);
$file_type=explode('.',$file_url);
$file_type=$file_type[count($file_type)-1];
$file_name=trim($new_name=='')?$file_name:urlencode($new_name).'.'.$file_type;
$file_type=fopen($file_url,'r'); //打开文件
//输入文件标签
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: ".filesize($file_url));
header("Content-Disposition: attachment; filename=".$file_name);
//输出文件内容
echo fread($file_type,filesize($file_url));
fclose($file_type);
}
//注意:调用方法:download("./201404/1.jpg");
下面几个回答的都tm没学过php在那水,下载的图片损坏,首先你已经下载了,文件没问题,但文件可能被压缩了, 加入这个选项 CURLOPT_ENCODING => "", 这是应对所有压缩的,一般都是gzip,上面不行就换成CURLOPT_ENCODING => "gzip",,如果还不行,把图片拖到浏览器看能不能打开,能打开说明是图片,只是格式window不支持,可能是webp格式的,getimagesize对webp格式的图片只会返回false,你要是想让他在window上显示,用php转化成jpg吧:
$img = imagecreatefromwebp('./response.webp');
$info=imagejpeg($img, 'a.jpg');
var_dump($info);
必须用CURL的方法下载,才能保证完整性
你用file_get_contents,如果对面返回404,那么就是你说的那种"破图情况"
当然也不要用 CURLOPT_FILE 方法下载:
$fp = fopen($local, "w");
curl_setopt($cp, CURLOPT_TIMEOUT, $time);
curl_setopt($cp, CURLOPT_HEADER, 0);
curl_setopt($cp, CURLOPT_FILE, $fp);
curl_exec($cp);
比如一张图片 50000字节,当你下到40000字节的时候就超时,此刻图片只能显示一半
最佳方法:
.........省略.........
$img = curl_exec($cp);
$info = curl_getinfo($cp);
curl_close($cp);
if ($info['http_code'] != 200) {
return false;
}
再把$img 存入文件
//这种操作比上面方法耗时慢了近一倍, 因为是现在先把请求的结果存入变量,再写入文件,所以是百分百完整性.
其次CURL可以模拟请求,对于一些带https或者302跳转的图片都有相应解决方法
---专注采集20年