1

I have built a custom form in Drupal 7. The form has a file type field which allows the user to upload an image. I'm using the below code in the submit function to save and re size the image:

function adddeals_submit($form, &$form_state){
    global $user;

    $file = $form_state['storage']['file'];
    // We are done with the file, remove it from storage.
    unset($form_state['storage']['file']);
    // Make the storage of the file permanent
    $file->status = FILE_STATUS_PERMANENT;
    // Save file status.
    file_save($file);
    //get the url for the saved file
    $url = file_create_url($file->uri);
    echo $url;
    echo '<br>';

    $destination = 'public://ImageThumbnail';
    $img = image_load($file->uri);
    image_resize($img, 200, 200);
    $result = image_save($img,$destination);
    echo $result;


    exit;
  }

The image is re-sizing and saving correctly as the $result is printing 1. I need to know how to get the URL for the re sized image. Am I missing something?

Thanks for you help.

  • I think in this case, you can get the URL by reloading the $img object as this object is updated when saving the resized image – Mika A. Nov 12 '13 at 7:48
1

I wouldn't use your approach because as you can see by yourself now you have no reference to the resized image, what I would do is use image_style_path :

function adddeals_submit($form, &$form_state){
    global $user;

    $file = $form_state['storage']['file'];
    unset($form_state['storage']['file']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    $url = file_create_url($file->uri);
    // this
    $derivative_uri = image_style_path($your_style, $file->uri);
    $url = image_style_create_derivative(image_style_load('your_style'), $file->uri, $derivative_uri);
}

This creates a folder in your files folder with your style name and stores the image there, then wherever in your code you want to get that image you just reutilize this code:

$derivative_uri = image_style_path($your_style, $file->uri);
$url = image_style_create_derivative(image_style_load('your_style'), $file->uri, $derivative_uri);

Drupal checks if an image is there and gives you back the $url, if it's not there it creates the image applying your style.

P.S. you need to register your style in configuration and once the style folder is created check it's permission settings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.