2013-02-14 68 views
0

我使用下面的代碼將圖像從url複製到我的web目錄的功能,但我不知道爲什麼有些圖像不能100%複製。從url複製後不是精確的圖像複製

這裏是我的web目錄http://www.aligatoor.pl/uploads/deals/2632b3802e8ed7abe83788dab605bbf7.jpg

錯圖像的副本,這裏的原始圖像http://infobuzer.pl/img/r4d3k/voucher/50e35a84c9038.jpg

function upload_file($file_path) 
{ 
    $deal_img_data=file_get_contents($file_path); 

    $file_name=md5($file_path).".jpg"; 

    if(!file_exists($file_name)) 
    { 
     $file=fopen($file_name,"w+"); 

     fwrite($file,$deal_img_data); 
    } 
} 

我也試過,捲曲,但它仍然無法正常複製一些圖片。

捲曲代碼:

$ch = curl_init ($url); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); 
$raw=curl_exec($ch); 
curl_close ($ch); 
$saveto=md5($url).".jpg"; 
if(file_exists($saveto)){ 
    unlink($saveto); 
} 
$fp = fopen($saveto,'x'); 
fwrite($fp, $raw); 
fclose($fp); 
+0

雖然不只是file_put_contents而不是fopen/fwrite? – 2013-02-14 21:45:04

+1

您可能只需指定「wb +」作爲標誌。 b表示二進制模式。這可能是原因。它可能認爲它是一個文本文件。 – 2013-02-14 21:46:52

+0

「wb +」和file_put_contents不起作用到 – Marek 2013-02-14 22:16:24

回答

0

你的功能工作正常

只要刪除舊的圖像,並嘗試重新下載。

還補充:

fclose($file); 
+0

不能用fclose – Marek 2013-02-14 22:16:49

-2

嘗試增加的set_time_limit(0)在函數的beggining

+0

它只有一個〜50K的文件,這個怎麼辦? – craig1231 2013-02-14 21:42:46

+0

它可能沒有幫助,但肯定會排除腳本在文件關閉前被殺的遠程可能性。 – horatio 2013-02-14 21:50:50

+0

不起作用 – Marek 2013-02-14 22:18:27

0

我不知道到底是什麼,你的問題的原因,但我面臨着類似的問題與文件搬運和我解決它使用這種方法:

if($handle =fopen($filename, "wb+")){ 
    if(flock($handle, LOCK_EX)) 
    { 
     fseek($handle, 0); 
     ftruncate($handle, 0); 

     fwrite($handle, $newcontent); 

     fflush($handle); 
     flock($handle, LOCK_UN); 
    } 
    fclose($handle); 
    } 

FLOCK()

編輯:處理圖像更好地使用圖像功能,如imagejpeg()imagecreatefromjpeg()更好的安全性和準確的結果。

例:

$im = @imagecreatefromjpeg($image); 
    if(is_bool($im)){ 
    die("Invalid Image detected!"); 
    } 
    else{ 

    if(!imagejpeg($im, $newpath)){ 
    die("Image not saved!"); 
    } 
    else{ 
    die("Image saved!"); 
    } 
    } 

EDIT2:添加這個而不是使用file_get_contents()函數

<?php 

$handle = fopen($file_path, "rb"); 
$deal_img_data = stream_get_contents($handle); 
fclose($handle); 

?> 
+0

不適用於 – Marek 2013-02-14 22:18:03

+0

您使用了哪一部分?你得到了什麼錯誤?你能提供你的試用嗎? – 2013-02-14 22:28:55

+0

我已經試過這個第一個你的代碼,並沒有任何錯誤,只是仍然不是確切的圖像副本。我也試過CURL,它仍然有一些圖像是好的,有些則沒有。 – Marek 2013-02-14 22:32:57

0

我找到怎樣的方式來做到這一點,因此,如果任何一個已經得到了類似的問題我的,他可以嘗試使用此功能:

function grab_image($url){ 
    $ch = curl_init ($url); 
    $saveto = md5($url).".jpg"; 
    $fp = fopen($saveto,'wb'); 
    curl_setopt($ch, CURLOPT_FILE, $fp); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_exec($ch); 
    curl_close($ch); 
    fclose($fp); 
}