代碼如上,原圖是可以開啟的,但下載到本地就損壞了。
試過header加檔案類型,PHP編碼也是utf-8,都沒用。
加ob_flush()活ob_clean()都沒用。
換成fopen函數也是損壞。
在此求助各位大神,非常感謝!!
補充:用這個也是損壞的http://segmentfault.com/q/1010000000156959
回複內容:
代碼如上,原圖是可以開啟的,但下載到本地就損壞了。
試過header加檔案類型,PHP編碼也是utf-8,都沒用。
加ob_flush()活ob_clean()都沒用。
換成fopen函數也是損壞。
在此求助各位大神,非常感謝!!
補充:用這個也是損壞的http://segmentfault.com/q/1010000000156959
原因很簡單,圖片被gzip了。
用file_get_contents("compress.zlib://".$url);
$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");
應該是對方的伺服器做了 判斷 用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 就可以了
使用十六進位編輯器開啟下載的圖片查看檔案頭
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;
}