2016-09-19 12 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)' 'と。 '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; 
} 
関連する問題