Skip to content

Instantly share code, notes, and snippets.

@RishiKulshreshtha
Last active October 21, 2016 09:50
Show Gist options
  • Save RishiKulshreshtha/eee2084770f718702c783471b6f48451 to your computer and use it in GitHub Desktop.
Save RishiKulshreshtha/eee2084770f718702c783471b6f48451 to your computer and use it in GitHub Desktop.
image_style_generate.module
<?php
/**
* Implements hook_node_insert to generate derivative images for the new inserted node in
* case they are not generated
* @param object $node
*/
function image_style_generate_node_insert($node) {
// REPLACE field_YOUR_IMAGE_FIELD WITH YOUR FIELD IMAGE NAME
if (isset($node->field_image['und'][0]['uri'])) {
$image_styles = array('image_style_1', 'image_style_2', 'image_style_3');
_generate_image_style($image_styles, $node->field_image['und'][0]['uri']);
}
if (isset($node->field_vertical_image['und'][0]['uri'])) {
$image_styles = array('image_style_4', 'image_style_5', 'image_style_6');
_generate_image_style($image_styles, $node->field_vertical_image['und'][0]['uri']);
}
if (is_array($node->field_image_gallery['und']) && !empty($node->field_image_gallery['und'])) {
$image_styles = array('image_style_1', 'thumbnail', 'image_style_6');
foreach ($node->field_image_gallery['und'] as $id => $uri) {
_generate_image_style($image_styles, $node->field_image_gallery['und'][$id]['uri']);
}
}
}
/**
* Implements hook_node_update to generate derivative images for the new updated node in
* case they are not generated
* @param object $node
*/
function image_style_generate_node_update($node) {
// REPLACE field_YOUR_IMAGE_FIELD WITH YOUR FIELD IMAGE NAME
if (isset($node->field_image['und'][0]['uri'])) {
$image_styles = array('image_style_1', 'image_style_2', 'image_style_3');
_generate_image_style($image_styles, $node->field_image['und'][0]['uri']);
}
if (isset($node->field_vertical_image['und'][0]['uri'])) {
$image_styles = array('image_style_4', 'image_style_5', 'image_style_6');
_generate_image_style($image_styles, $node->field_vertical_image['und'][0]['uri']);
}
if (is_array($node->field_image_gallery['und']) && !empty($node->field_image_gallery['und'])) {
$image_styles = array('image_style_1', 'thumbnail', 'image_style_6');
foreach ($node->field_image_gallery['und'] as $id => $uri) {
_generate_image_style($image_styles, $node->field_image_gallery['und'][$id]['uri']);
}
}
}
/**
* Generates the needed image styles by the image uri if they are not already generated
* @param array $image_styles
* @param string $image_uri
*/
function _generate_image_style($image_styles, $image_uri) {
//This should be changed to your image styles names.
foreach ($image_styles as $style) {
$derivative_uri = image_style_path($style, $image_uri);
file_exists($derivative_uri) || image_style_create_derivative(image_style_load($style), $image_uri, $derivative_uri);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment