doushuo2834 2012-02-22 18:20
浏览 24
已采纳

使用imagecopyresampled调整Drupal中上传图像的大小

I'm trying to resize an image that is uploaded to Drupal via a form. The code I have for it is:

//Image resizing
//Get file and if it's not the default one - resize it.
$img = file_load($form_state['values']['event_image']);
if($img->fid != 1) {
  //Get the image size and calculate ratio
  list($width, $height) = getimagesize($img->uri);
  if($width/$height > 1) {
    $new_width = 60;
    $new_height = $height/($width/60);
  } else if($width/$height < 1) {
    $new_height = 60;
    $new_width = $width/($height/60);
  } else {
    $new_width = 60;
    $new_height = 60;
  }
  //Create image
  $image_p = imagecreatetruecolor($new_width, $new_height);
  $ext = strtolower(pathinfo($img->uri, PATHINFO_EXTENSION));
  if($ext == 'jpeg' || $ext == 'jpg') {
    $image = imagecreatefromjpeg($img->uri);
  } else {
    $image = imagecreatefrompng($img->uri);
  }
  //Resize image
  imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  //Save image as jpeg
  imagejpeg($image_p, file_create_url($img->uri), 80);
  //Clean up
  imagedestroy($image_p);
  //Store the image permanently.
  $img->status = FILE_STATUS_PERMANENT;
}
file_save($img);

So what I'm trying to achieve is to save the new file (with the smaller size) over the old one that got uploaded.

The problem I'm getting is PHP throws a warning on imagejpeg($image_p, file_create_url($img->uri), 80); saying:

Warning: imagejpeg() [function.imagejpeg]: Unable to open 'http://localhost:8888/drupal/sites/default/files/pictures/myimage.png' for writing: No such file or directory in event_creation_form_submit()

Because of this, the image isn't resizing. Does anyone know what I'm doing wrong?

Thanks,

  • 写回答

1条回答 默认 最新

  • dptrmt4366 2012-02-24 11:03
    关注

    As Clive pointed out - the fix was to use image_scale. Here is an extract of working code:

    //Image resizing
    //Get file and if it's not the default one - resize it.
    $img = file_load($form_state['values']['event_image']);
    if($img->fid != 1) {
      //Get the image size and calculate ratio
      $newImage = image_load($img->uri);
      list($width, $height) = getimagesize($img->uri);
      if($width/$height >= 1) {
        image_scale($newImage, 60);
      } else {
        image_scale($newImage, null, 60);
      }
      //Save image
      image_save($newImage);
      $img->status = FILE_STATUS_PERMANENT;
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟