2017-09-11 20 views
1
function grab_image($url, $saveto){ 
     $url = $url; 
     $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); 
     if(file_exists($saveto)){ 
      unlink($saveto); 
     } 
     $fp = fopen($saveto, 'w'); 
     fwrite($fp, $raw); 
     fclose($fp); 
    } 
$link = 'https://images-na.ssl-images-amazon.com/images/I/415lKuJC%2B2L.jpg'; 
grab_image($link, '/tmp/415lKuJC%2B2L.jpg'); 

錯誤時保存到本地文件(0字節),我覺得這個環節有特殊字符%2B錯誤0字節當保存圖像到本地或其他服務器

+0

你'$ saveto'路徑是錯誤的。把它改成'/tmp/test.jpg' – spinsch

回答

0

嘗試在函數調用中添加文件名,像下面:

grab_image($link, "/tmp/new_file_name.jpg"); 
0

替代解決方案搶與原文件名的文件:

function grab_image($url, $savePath = getcwd()) 
{ 
    $path = $savePath.'/'.basename($url); 
    if (file_exists($path)) { 
     unlink(); 
    } 
    copy($url, $path); 
} 

$link = 'https://images-na.ssl-images-amazon.com/images/I/415lKuJC%2B2L.jpg'; 
grab_image($link); 
相關問題