forzar la generación del estilo de imagen en el nodo guardar


Respuestas:


12

Sí, puede implementar hook_node_insert()y hook_node_update()en un módulo personalizado y crear las imágenes allí utilizando las funciones de API de imagen. Por ejemplo

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);
    }
  }
}

se ve bien gracias! pero, ¿podría saber cómo obtener el valor de los elementos de la colección de campos relacionados con mi tipo de nodo?
— sinini


He notado ahora que las imágenes generadas no cambian de tamaño, solo se almacenan en el tamaño original. ¿alguna vez te sucedió esto y podrías tener alguna idea de cómo resolverlo?
— sinini


La vida de D7 es limitada, pero en caso de que alguien se encuentre con esto como lo hice hoy, una corrección. image_style_create_derivative () espera una matriz para el primer parámetro, por lo que la línea debe ser: image_style_create_derivative (image_style_load ($ style_name), $ file-> uri, $ derivative_uri);
— Marque el

9

Las dos respuestas con bloques de código son en su mayoría correctas, excepto que pasan por alto una cosa importante:

Se espera que el primer argumento de image_style_create_derivative sea una matriz de estilo de imagen.

Lo que están pasando es solo el nombre del estilo. En el foreach si agrega:

$style = image_style_load($style_name);

luego cambie $ style_name a $ style en la función image_style_create_derivative, debería funcionar como se espera y generar la imagen con estilo.

image_style_create_derivative($style, $file->uri, $derivative_uri);

Espero que ayude a cualquier otra persona que tenga este problema.


4

Gracias por su ayuda Clive, toda mi función para los elementos de la colección de campo: (otra publicación útil de su parte: Acceso a una colección de campo )

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);
    }
  }
}


0

Se recomienda usar hook_node_insert () y hook_node_update () y verificar si no se generan los derivados de imagen necesarios, luego generarlos, de lo contrario, no haga nada.

/**
 * Implements hook_node_insert to generate derivative images for the new inserted node in
 * case they are not generated
 * @param object $node
 */
function YOUR_MODULE_node_insert($node) {
  //REPLACE field_YOUR_IMAGE_FIELD WITH YOUR FIELD IMAGE NAME
  if(isset($node->field_YOUR_IMAGE_FIELD['und'][0]['uri'])) {
    _generate_image_style($node->field_YOUR_IMAGE_FIELD['und'][0]['uri']);
  }
}

/**
 * Implements hook_node_update to generate derivative images for the new updated node in
 * case they are not generated
 * @param object $node
 */
function YOUR_MODULE_node_update($node) {
  //REPLACE field_YOUR_IMAGE_FIELD WITH YOUR FIELD IMAGE NAME
  if(isset($node->field_YOUR_IMAGE_FIELD['und'][0]['uri'])) {
    _generate_image_style($node->field_YOUR_IMAGE_FIELD['und'][0]['uri']);
  }
}

/**
 * Generates the needed image styles by the image uri if they are not already generated
 * @param string $image_uri
 */
function _generate_image_style($image_uri) {
  //This should be changed to your image styles names.
  $image_styles = array('image_style_name1', 'large_image', 'promo_image');
  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);
  }
}

Nota: Si su campo de imagen toma varias imágenes, entonces debe recorrerlas de esa manera:

if(isset($node->field_main_image['und']) && is_array($node->field_main_image['und'])) {
  foreach($node->field_main_image['und'] as $delta => $image_field) {
    _generate_image_style($node->field_YOUR_IMAGE_FIELD['und'][$delta]['uri']);
  }
}

La generación de estilos de imagen se toma desde aquí.

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.