【问题标题】:Images corrupted after copying复制后图像损坏
【发布时间】:2017-01-27 04:37:49
【问题描述】:

尝试从远程服务器复制图像以用作我的 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 );
    }
  }
}

这是一个显示我的意思的屏幕截图(左 - 原始图像;右 - 我的服务器上的副本):

【问题讨论】:

  • 在调用set_post_thumbnail 之前尝试使用$attachData = wp_generate_attachment_metadata($attachment_id, $filename);wp_update_attachment_metadata($attach_id, $attachData);,看看生成的图像是否有所改善。确保在脚本的某处也require_once( ABSPATH . 'wp-admin/includes/image.php' );
  • 问题在于,可以通过 $local_url 中存储的 url 访问的图像已经损坏。这是在创建附件之前。

标签: php wordpress image


【解决方案1】:

我认为您的 download_url( $url, $timeout_seconds ) 功能无法正常工作(您无法捕获网络/其他错误,这就是您损坏图像的原因),我也不认为 timeout 参数真的需要下载一个网址...

要解决这个问题,最好把这个函数改写成这样:

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;
}

【讨论】:

    猜你喜欢
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 2022-01-14
    • 2012-04-13
    • 1970-01-01
    相关资源
    最近更新 更多