首页 > PHP远程下载图片损坏

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://.com/q/1010000000156959


$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");


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


//下载保存图片
function save_image($inPath,$outPath)
{ //Download images from remote server
$imgUrl=$inPath;
$in= fopen($inPath, "rb");
$out= fopen($outPath, "wb");

//http开头验证
if (strpos($imgUrl, "http") !== 0) {
    $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
    return;
 }
 //获取请求头并检测死链
$heads = get_headers($imgUrl);
if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
    return false;
}
while ($chunk = fread($in,8192))
{
    $re=fwrite($out, $chunk, 8192);

}

    fclose($in);
    fclose($out);

if($re)
{
    var_dump('success');
    return  true;
}
else
{
    var_dump('false');
    return false;
}

}

//创建文件夹
function mkdirs($dir,$mode=0777)
{
if(is_dir($dir)||@mkdir($dir,$mode)){
return true;
}
if(!mkdirs(dirname($dir),$mode)){
return false;
}
return @mkdir($dir,$mode);
}

//存储图片
function download_img($url,$dir_prefix)
{
$path=explode('/',$url);
$domain='http://'.$path[2];
$newpath=$dir_prefix.explode($domain,$url)[1];
//mkdir
$d=explode('/',$newpath);
$dir=explode($d[count($d)-1],$newpath)[0];
mkdirs($dir);
$filename = $newpath;
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
$img = save_image($url,$newpath);

}

return $domain;

}


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


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


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


应该是对方的服务器做了 判断 用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 就可以了

【热门文章】
【热门文章】