2012-02-22 98 views
0

我正在嘗試調整通過表單上傳到Drupal的圖像大小。我有它的代碼是:在Drupal中使用imagecopyresampled調整上傳圖像的大小

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

Drupal的圖像大小調整功能內置的權利有沒有任何理由,你不能使用這些? – Clive 2012-02-22 19:25:18

+0

嗨克萊夫,我不知道Drupal有這些 - 它只是你在談論的http://api.drupal.org/api/drupal/includes%21image.inc/function/image_resize/7? – KerrM 2012-02-22 19:29:24

+1

有不少,['image_scale'](http://api.drupal.org/api/drupal/includes%21image.inc/function/image_scale/7),['image_crop'](http:// api.drupal.org/api/drupal/includes%21image.inc/function/image_crop/7),['image_scale_and_crop'](http://api.drupal.org/api/drupal/includes%21image.inc/function/image_scale_and_crop/7),['image_rotate'](http://api.drupal.org/api/drupal/includes%21image.inc/function/image_rotate/7),我想其他幾個人 – Clive 2012-02-22 19:33:09

回答

2

正如克萊夫指出的 - 修復是使用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; 
    }