PHP远程下载图片损坏



 <?php
$pic=file_get_contents('http://i2.tietuku.com/1b776066fa782b78.jpg');
ob_flush();file_put_contents('1.jpg',$pic);
?>

代码如上,原图是可以打开的,但下载到本地就损坏了。
试过header加文件类型,PHP编码也是utf-8,都没用。
加ob_flush()活ob_clean()都没用。
换成fopen函数也是损坏。

在此求助各位大神,非常感谢!!
补充:用这个也是损坏的 http://segmentfault.com/q/1010000000156959

下载 远程 php

bterm 9 years ago

感谢各位的回答,每个代码我都测试了,在本地还是坏的。
应该是因为贴图库某些服务器的问题,或者是我本地虚拟机的问题。
那个网站是默认全部开放外链,应该没有盗链问题,准备换个服务器试试。
总之谢谢三位回答,采纳了第一位的答案,辛苦各位!

zirok answered 9 years ago

casperjs表示你们上面回答的问题太复杂了,万一别人加个header判断就又挂了

kyech answered 9 years ago

使用十六进制编辑器打开下载的图片查看文件头

dxj5p answered 9 years ago

应该是对方的服务器做了 判断 用file_get_contents() 获得的数据是有误的
测试 使用curl是可以获取的
写一个自定义函数


 function curl_get_contents($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

然后用curl_get_contents 代替file_get_contents 就可以了

我有一个大阴谋 answered 9 years ago


 $ch = curl_init('http://example.com/1b776066fa782b78.jpg');
$fp = fopen('/my/folder/1b776066fa782b78.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

输出的时候带个头 header("content-type: image/your_image_type");

防爆的氪金坚菊 answered 9 years ago

原因很简单,图片被gzip了。
用file_get_contents("compress.zlib://".$url);

百合魔神晓美焰 answered 9 years ago

Your Answer