Cómo conectarse a la generación de miniaturas de WordPress

5 minutos de lectura

Me gustaría realizar un procesamiento personalizado en un determinado tamaño de miniatura en WordPress con ImageMagick más allá de la funcionalidad normal de WordPress y no estoy muy seguro de cómo hacerlo.

Así que agrego mi nuevo tamaño de miniatura:

add_image_size( 'new-thumb', 100, 100 );

Y luego aquí es donde no estoy seguro de dónde debo engancharme. Antes de que la copia final de la miniatura se guarde en WordPress, quiero realizarle un procesamiento personalizado. El psuedo código básico para lo que quiero es:

The_hook_or_action_that_fires_when_a_thumbnail_is_saved() {

    if (<Thumbnail Being Generated> == 'new-thumb') {
      $thumb_file="the thumbnail image we are about to save";
      $thumbfile="do some imagemagic stuff here";
    }

    save_thumbnail;
}

Puedo manejar las cosas de imagemagick, pero no estoy seguro de cómo / dónde conectar este procesamiento de miniaturas personalizado.

¡Cualquier consejo sería muy apreciado!

Gracias @brasofilo por señalarme en la dirección correcta…

Investigué un poco y descubrí esto. Puede conectarse a wp_generate_attachment_metadata y manipular la imagen.

Lo básico de lo que estaba tratando de hacer es cambiar el tamaño de una imagen a un tamaño específico (miniatura de “marcas”), luego expandir el lienzo para esa miniatura a una altura y ancho estáticos con un fondo blanco.

En caso de que alguien tenga una situación similar, pensé en pegar algún código. Podría limpiarse para eliminar el reabastecimiento de cada tipo de imagen. El único problema con este código es que si el tamaño de la imagen original es menor que el tamaño deseado de la miniatura, no se generará (que es la funcionalidad de WordPress).

add_image_size( 'brands', 200, 168 );

add_filter('wp_generate_attachment_metadata','replace_uploaded_image');
function replace_uploaded_image($image_data) {

    // if there is no brands image : return
    if ( !isset($image_data['sizes']['brands']) ) 
        return $image_data;

    //Set our desired static height / width (200px * 168px)
    $staticWidth  = 200;
    $staticHeight = 168;

    // paths to the uploaded image and the large image
    $upload_dir            = wp_upload_dir();
    $brands_image_location = $upload_dir['path'] . "https://stackoverflow.com/" . $image_data['sizes']['brands']['file'];

    // set our temp image file
    $brands_image_location_tmp = "$brands_image_location.tmp";

    // get the attributes of the source image
    list($imageWidth, $imageHeight, $imageType, $imageAttr) = getimagesize($brands_image_location);

    // there are different php functions depending on what type of image it is, so check the type
    switch($imageType) {
        //GIF
        case 1: 
            //Create a 200x168 white canvas
            $newimage=imagecreatetruecolor($staticWidth,$staticHeight);
            $white=imagecolorallocate($newimage, 255, 255, 255);
            imagefill($newimage,0,0,$white);

            //Calculate where the image should start so its centered
            if($imageWidth == $staticWidth)  { $x_pos = 0; } else { $x_pos = round( ($staticWidth - $imageWidth) / 2 ); }
            if($imageHeight == $staticHeight) { $y_pos = 0; } else { $y_pos = round( ($staticHeight - $imageHeight) / 2 ); }

            //Copy the source image to the new canvas
            $src = imagecreatefromgif($brands_image_location);
            imagecopy($newimage, $src, $x_pos, $y_pos, 0, 0, $imageWidth, $imageHeight);
            imagegif($newimage,$brands_image_location_tmp);

            // delete the uploaded image
            unlink($brands_image_location);

            // rename the temporary brands image
            rename($brands_image_location_tmp, $brands_image_location);

            // update image metadata and return them
            $image_data['sizes']['brands']['width'] = $staticWidth;
            $image_data['sizes']['brands']['height'] = $staticHeight;

            break;

        //JPG
        case 2:
            //Create a 200x168 white canvas
            $newimage=imagecreatetruecolor($staticWidth,$staticHeight);
            $white=imagecolorallocate($newimage, 255, 255, 255);
            imagefill($newimage,0,0,$white);

            //Calculate where the image should start so its centered
            if($imageWidth == $staticWidth)  { $x_pos = 0; } else { $x_pos = round( ($staticWidth - $imageWidth) / 2 ); }
            if($imageHeight == $staticHeight) { $y_pos = 0; } else { $y_pos = round( ($staticHeight - $imageHeight) / 2 ); }

            //Copy the source image to the new canvas
            $src = imagecreatefromjpeg($brands_image_location);
            imagecopy($newimage, $src, $x_pos, $y_pos, 0, 0, $imageWidth, $imageHeight);
            imagejpeg($newimage,$brands_image_location_tmp);

            // delete the uploaded image
            unlink($brands_image_location);

            // rename the temporary brands image
            rename($brands_image_location_tmp, $brands_image_location);

            // update image metadata and return them
            $image_data['sizes']['brands']['width'] = $staticWidth;
            $image_data['sizes']['brands']['height'] = $staticHeight;

            break;

        //PNG
        case 3:
            //Create a 200x168 white canvas
            $newimage=imagecreatetruecolor($staticWidth,$staticHeight);
            $white=imagecolorallocate($newimage, 255, 255, 255);
            imagefill($newimage,0,0,$white);

            //Calculate where the image should start so its centered
            if($imageWidth == $staticWidth)  { $x_pos = 0; } else { $x_pos = round( ($staticWidth - $imageWidth) / 2 ); }
            if($imageHeight == $staticHeight) { $y_pos = 0; } else { $y_pos = round( ($staticHeight - $imageHeight) / 2 ); }

            //Copy the source image to the new canvas
            $src = imagecreatefrompng($brands_image_location);
            imagecopy($newimage, $src, $x_pos, $y_pos, 0, 0, $imageWidth, $imageHeight);
            imagepng($newimage,$brands_image_location_tmp);

            // delete the uploaded image
            unlink($brands_image_location);

            // rename the temporary brands image
            rename($brands_image_location_tmp, $brands_image_location);

            // update image metadata and return them
            $image_data['sizes']['brands']['width'] = $staticWidth;
            $image_data['sizes']['brands']['height'] = $staticHeight;

            break;

    }

    return $image_data;
}

  • ¡Brillante! Todavía funciona. Sin embargo, hay un cambio importante mencionado en esta respuesta de @Albin: stackoverflow.com/a/26699842

    – Tomas Ebert

    12 de mayo de 2021 a las 13:26

avatar de usuario
brasofilo

En mi biblioteca tengo lo siguiente:

Establecer un nombre personalizado para las miniaturas generadas

Manipulación muy interesante de nombres de pulgares y cultivos.. Consulte las preguntas y respuestas originales vinculadas en este.

Usos:

Utilice automáticamente imágenes redimensionadas en lugar de originales

Usos:

  • wp_generate_attachment_metadata

¿Cómo agregar automáticamente esquinas redondeadas a las miniaturas?

Usos:

¿Cómo exigir una dimensión de imagen mínima para cargar?

Usos:

Organiza las subidas por año, mes y día

Usos:

Me gustaría sugerir un cambio para que funcione con el complemento de regeneración de miniaturas.

$upload_dir = wp_upload_dir();
$brands_image_location = $upload_dir['basedir']."https://stackoverflow.com/".dirname($image_data['file']) . "https://stackoverflow.com/" . $image_data['sizes']['brands']['file'];
$brands_image_location = $brands_image_location.'.tmp';

Esto se debe a que wp_upload_dir devuelve la ruta del año-mes actual, pero algunas imágenes cargadas anteriormente podrían tener una ruta diferente.

  • ¡Gracias! Esta respuesta es más un comentario a una respuesta de @ChuckMac, que se encuentra aquí stackoverflow.com/a/14218764

    – Tomas Ebert

    12 mayo 2021 a las 13:25


¿Ha sido útil esta solución?