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 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿