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

时间:2012-02-22 18:20:42

标签: php image drupal resize

我正在尝试调整通过表单上传到Drupal的图像的大小。我的代码是:

//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);

所以我想要实现的是将新文件(尺寸较小)保存到上传的旧文件中。

我遇到的问题是PHP在imagejpeg($image_p, file_create_url($img->uri), 80);上发出警告:

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()

因此,图像没有调整大小。有谁知道我做错了什么?

谢谢,

1 个答案:

答案 0 :(得分:2)

正如Clive指出的那样 - 解决方法是使用image_scale。以下是工作代码的摘录:

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