Drupal - force image style generation on save node
Yes - you can implement hook_node_insert()
and hook_node_update()
in a custom module and create the images there using image API functions. For example
function MYMODULE_node_insert($node) {
// Get some field items from a field called 'field_photo.
if ($image_items = field_get_items('node', $node, 'field_photo')) {
$image_item = array_shift($image_items);
// Load the associated file.
$file = file_load($image_item['fid']);
// An array of image styles to create.
$image_styles = array('style_1', 'style_2');
foreach ($image_styles as $style_name) {
// Get the location of the new image.
$derivative_uri = image_style_path($style_name, $file->uri);
// Create the image.
image_style_create_derivative($style_name, $file->uri, $derivative_uri);
}
}
}
The two answers with blocks of code are mostly correct except they are overlooking one major thing:
The first argument of image_style_create_derivative is expected to be an image style array.
What they're passing is just the name of the style. In the foreach if you add:
$style = image_style_load($style_name);
then change $style_name to $style in the image_style_create_derivative function it should work as expected and generate the styled image.
image_style_create_derivative($style, $file->uri, $derivative_uri);
Hope that helps anyone else having this issue.
Thanks for your help Clive, my whole function for the field collection items: (another helpful post from you: Accessing a field collection)
function channelportal_gallery_node_update($node) {
//get all the id's from the field collection values
$galleryimages = field_get_items('node', $node, 'field_gallery_and_caption');
$fieldcollectionids = array();
foreach ($galleryimages as $key => $value) {
$fieldcollectionids[] = $value['value'];
}
// Load up the field collection items
$items = field_collection_item_load_multiple($fieldcollectionids);
foreach ($items as $item) {
$image_item = field_get_items('field_collection_item', $item, 'field_gallery_image');
// Load the associated file.
$file = file_load($image_item[0]['fid']);
// An array of image styles to create.
$image_styles = array('gallery_big', 'gallery_thumbnail');
foreach ($image_styles as $style_name) {
// Get the location of the new image.
$derivative_uri = image_style_path($style_name, $file->uri);
// Create the image.
image_style_create_derivative($style_name, $file->uri, $derivative_uri);
}
}
}