2016-09-19 2 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; 
} 
관련 문제