[Drupal] How to programmatically apply an image style to an image in a Drupal 7 site?
In one of my project I had a requirement to create an image in a particular image style in a specific folder, when uploading the image itself. In this article I will be explaining how to achieve this using the function image_style_create_derivative in drupal 7 to create an image in a particular image style. One another advantage of this function is that this will create the destination folder if it does not already exist.
The parameters of this function are,
- $style - The $style is an image style array. If the image style is already created using configuration, we can get it by using the function image_style_load.
- $source - The $source is the full path to the original image.
- $destination - The $destination is the full path to the destination.
In order to create the image in an image style 'thumbnail' I have added the following code in the node_insert hook so that it will create the image when creating the node itself.
/**
* Implements the hook_node_insert.
* Applying the image styles and store it in the destination directory.
*
* @param object $node
*/
function mymodule_node_insert($node) {
if ($node->type == 'image') {
$fid = $node->field_image[$node->language][0]['fid'];
$style = image_style_load('thumbnail');
$file = file_load($fid);
$source = $file->uri;
$destination = "full/path/to/destination/filename";
image_style_create_derivative($style, $source, $destination);
}
}
The above code will create the image in the image style 'thumbnail' in the destination folder when creating the node itself.
References:
http://api.drupal.org/api/drupal/modules!image!image.module/function/im…