2016-09-19 186 views
5

試圖從遠程服務器複製圖像以在我的WordPress網站中使用縮略圖。複製後,某些圖像會損壞。複製後圖像損壞

這裏是我的代碼:

$url = 'http://media.cultserv.ru/i/1000x1000/'.$event->subevents[0]->image; 
$timeout_seconds = 100; 
$temp_file = download_url($url, $timeout_seconds); 

if(!is_wp_error($temp_file)) { 
    $file = array(
    'name' => basename($url), 
    'type' => wp_check_filetype(basename($url), null), 
    'tmp_name' => $temp_file, 
    'error' => 0, 
    'size' => filesize($temp_file), 
); 
    $overrides = array(
    'test_form' => false, 
    'test_size' => true, 
    'test_upload' => true, 
); 
    $results = wp_handle_sideload($file, $overrides); 
    if(empty($results['error'])) { 
    $filename = $results['file']; 
    $local_url = $results['url']; 
    $type = $results['type']; 
    $attachment = array(
     'post_mime_type' => $results['type'], 
     'post_title' => preg_replace('/.[^.]+$/', '', basename($results['file'])), 
     'post_content' => '', 
     'post_status' => 'inherit', 
     'post_type' => 'attachment', 
     'post_parent' => $pID, 
    ); 
    $attachment_id = wp_insert_attachment($attachment, $filename); 
    if($attachment_id) { 
     set_post_thumbnail($pID, $attachment_id); 
    } 
    } 
} 

下面是截圖,顯示我的意思 - (左原始圖像;右鍵 - 複製我的服務器上):

screenshot

+0

嘗試使用'$ attachData = wp_generate_attachment_metadata($ attachment_id,$文件名);'和'wp_update_attachment_metadata($ attach_id,$ attachData); 'beofre調用'set_post_thumbnail'並查看得到的圖像是否改進。確保require_once(ABSPATH。'wp-admin/includes/image.php');'在腳本的某處。 – fyrye

+0

問題是,存儲在$ local_url中的url可訪問的圖像已損壞。這是在附件創建之前。 –

回答

1

我認爲你download_url($url, $timeout_seconds)函數無法正常工作(您無法捕獲網絡/其他錯誤,這就是爲什麼您的圖像已損壞),我也不認爲超時參數確實需要下載url ...

爲了解決這個問題,最好給這個函數改寫成這樣:

function download_url($url) 
{ 
    $saveto = 'temp.jpg'; // generate temp file 
    $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); 
    if (curl_errno($ch)) { 
     curl_close($ch); 
     return false; 
     // you probably have a network problem here. 
     // you need to handle it, for example retry or skip and reqeue the image url 
    } 
    curl_close($ch); 
    if (file_exists($saveto)) { 
     unlink($saveto); 
    } 
    $fp = fopen($saveto, 'x'); 
    fwrite($fp, $raw); 
    fclose($fp); 
    return $saveto; 
}