Redimensionar imágenes por lotes automáticamente mediante la adición de espacios en blanco (es decir, sin distorsionar las proporciones originales)

Tengo varias fotos, cada una de las cuales tiene un tamaño y una resolución diferentes. Me gustaría hacerlos todos cuadrados: la resolución no es crítica y puede diferir según la foto, pero cada imagen de salida debe ser cuadrada en proporción.

También debo asegurarme de que la foto original no esté distorsionada o sesgada de ninguna manera. Supongo que esto se puede hacer agregando un espacio en blanco en la parte inferior de una foto rectangular horizontal (por ejemplo), pero podría haber otras formas de lograr esto. ...

¡Cualquier ayuda sería genial!

Gracias

Respuestas (3)

Puede usar ImageMagick para cambiar el tamaño de la imagen y colocarla en un lienzo más grande con un fondo blanco. Si usa Mac o Linux, puede procesar archivos en un bucle for:

mkdir output
for i in *.jpg ; do
   convert "$i" -resize 4096x4096 -gravity center -background white -extent 4096x4096  "output/${i%.jpg}-processed.jpg"
done

Puede utilizar parallelpara procesar varios archivos simultáneamente:

mkdir output
for i in *.jpg ; do
   echo convert \"$i\" -resize 4096x4096 -gravity center -background white -extent 4096x4096  \"output/${i%.jpg}-processed.jpg\"
done | parallel

Hice algo similar para crear imágenes que tenían exactamente las mismas dimensiones para una presentación de diapositivas html, incluso si el archivo original había sido recortado o tenía una orientación vertical u horizontal. Utilicé gimp y un script de esquema para facilitar el proceso, ya que esta variación en el tamaño y la proporción de entrada hizo que el proceso fuera un fastidio. Sin embargo, no lo automaticé por completo, ya que solo estaba haciendo cinco imágenes a la vez y soy un principiante autodidacta en la codificación. Aun así, esto corrió a poco más de cien líneas de código.
El proceso fue más o menos el siguiente:

  1. Si el ancho de la imagen de entrada es mayor que la altura, escale la imagen al ancho de destino por la altura original x (ancho original/ancho de destino). Alternativamente, altura objetivo por ancho original x (altura original / altura objetivo).
  2. Cambie el tamaño del lienzo al ancho de destino por la altura de destino con las compensaciones centradas.
  3. Aplane y guarde el archivo.

listado de códigos

;; -*-scheme-*-
;; dmkonlinux 2014
;; resizes files larger than 1024 by 1024 to 1024 pixels on the longest side then applies a black canvas to create a 1024 by 1024 pixel square image for "1024by1024 x.jpg"
;; add ability to resize 1080 by 1435, 75% quality sRGB optomised, progressive, baseline, strip exif for "1080by1435 x.jpg"
;; tested on Ubuntu 17.10 and Gimp 2.8.22

(define (script-fu-dmkonlinux-web-image2    image                       ;define function and parameters in order of SF statements at end ie SF-IMAGE=image SF-DRAWABLE=drawable
                drawable
                option_size
                adjustment_number)                          
(let*   (                                                           ;define variables
    (width (car (gimp-image-width image)))                      ;use start of gimps image width variable
    (height (car (gimp-image-height image)))                    ;use start of gimps image height variable
    (targetwidth)                                                   ;a variable for the target width dependant on option_size
    (targetheight)                                              ;a variable for the target height dependant on option_size
    )
    (gimp-image-undo-group-start image)                     ;start an undo group for the image
    (gimp-context-set-interpolation 2)                          ;sets the interpolation method to (2) cubic
    (gimp-context-set-default-colors)                           ;sets the foreground / backgroud colours to default (black / white)
    (gimp-context-swap-colors)                                  ;swops the foreground / background colours

    (cond   ((= option_size 0) (set! targetwidth 1024)          ;if option_size is 0 (1024x1024) set targetwidth to 1024
                   (set! targetheight 1024))                        ;if option_size is 0 (1024x1024) set targetheight to 1024
        ((= option_size 1) (set! targetwidth 1435)              ;if option_size is 1 (1080x1435) set targetwidth to 1435
                   (set! targetheight 1080))                        ;if option_size is 1 (1080x1435) set targetheight to 1435
    )

    (if (> width height)
        (gimp-image-scale image targetwidth (/ height (/ width targetwidth)))       ;then scale image to width targetwidth by new height (divide height by ratio of width divided by targetwidth)
        (gimp-image-scale image (/ width (/ height targetheight)) targetheight)     ;else scale to...
    )
    (set! width (car (gimp-image-width image)))                 ;reset width and height to new dimensions
    (set! height (car (gimp-image-height image)))
    (gimp-image-resize image targetwidth targetheight (/ (- targetwidth width) 2) (/ (- targetheight height) 2))    ;resize canvas to targetwidth by targetheight with offsets centered
    (gimp-image-flatten image)                          ;flatten image alpha to background colour
    (gimp-image-undo-group-end image)                       ;end an undo group
)

(let*   (                                       ;define some local variables
    (drawable (car (gimp-image-get-active-drawable image)))             ;drawable has changed so this finds the drawable layer that is needed for file-web-export
    (dir_name)                                  ;define variable dir_name for save proceedure
    (filename)                                  ;define variable filename for save proceedure
    (filenumber adjustment_number)                          ;define variable filenumber for save proceedure abd set to adjustment_number
    (comment "")                                    ;define variable comment for save proceedure
    )

    (cond   ((= option_size 0) (set! filename "1024by1024 ")                                ;if option_size is 0 (1024x1024) then filename = 1024by1024
                   (set! dir_name "Desktop/")                                   ;and dir_name is users desktop
                   (set! comment "resized to 1024x1024"))                           ;and comment is resized to 1024x1024
        ((= option_size 1) (set! filename "1080by1435 ")                                ;if option_size is 1 (1080x1435) then filename = 1080by1435
                   (set! dir_name "Desktop/")                                   ;and dir_name is users desktop
                   (set! comment "resized to 1080x1435"))                           ;and comment is resized to 1080x1435
    )

    (set! filename (string-append dir_name filename (number->string filenumber) ".jpg"))    ;set filename to dir_name + filename + filenumber (number converted to string) + ".jpg"

    (gimp-image-detach-parasite image "gimp-metadata")                  ;lifted from gimp-save-for-web on github these are intended to remove the exif info and file save settings before saving
    (gimp-image-detach-parasite image "exif-data")
    (gimp-image-detach-parasite image "jpeg-settings")


    (gimp-image-set-filename image filename)                        ;set gimps filename to reflect the file as saved
    (file-jpeg-save 1 image drawable filename filename 0.75 0 1 1 comment 0 1 0 0)      ;this proceedure is save as jpeg.  params only used if used NON-INTERACRIVE (0)
)                                               ;   1 : run NON-INTERACTIVE  
                                                ;   image : variable containing image id
                                                ;   drawable : variable containing drawable id
                                                ;   filename : variable containing image filename
                                                ;   raw_filename : variable containing image filename
                                                ;   0.75 : value for quality setting
                                                ;   0 : value for smoothing (off)
                                                ;   1 : value for optimisation (on)
                                                ;   1 : value for progressive (on)
                                                ;   comment : variable containing comment
                                                ;   0 : value for subsampling (chroma quatered)
                                                ;   1 : value for baseline jpeg (on)
                                                ;   0 : value for restart markers (off)
                                                ;   0 : value for dct method (integer)

(gimp-displays-flush)                           ;flush all pending updates of image manipulations to the user interface
(gimp-image-clean-all image)                ;resets dirty count to 0 and allows closing without save dialogue.
)

(script-fu-register "script-fu-dmkonlinux-web-image2"
_"dmkonlinux web image resize2"
_"scale image to 1024 by 1024 or 1080 by 1435 and add background colour canvas"
"dmkonlinux"
"dmkonlinux, 2014"
"Sept 2014"
"*"
SF-IMAGE    "Input Image" 0                                                 ;the current image id
SF-DRAWABLE "Input Drawable" 0                                      ;the current drawable id
SF-OPTION   "Size"          '("1024 by 1024" "1080 by 1435")                ;display option box widget with list option 0, option 1
SF-ADJUSTMENT   "File number"       '(1 1 20 1 10 0 SF-SPINNER)         ;display adjustment box widget with lstart value, lower / upper values, step_inc, page_inc, digits after decimal point, type slider or spinner
)

(script-fu-menu-register "script-fu-dmkonlinux-web-image2"
         "<Image>/dmkonlinux's")

;(gimp-image-get-filename (gimp-item-get-image item)
;(gimp-image-list) returns number of open images and array of image id's ie (2#(2 1))
;(cadr(gimp-image-list) returns the the first item of the tail of gimp-image-list ie #(2 1)
;(aref(cadr(gimp-image-list)) 0) returns the value at array ref 0 ie 2
;(gimp-get-parasite-list) returns global parasite list ie (1 ("jpeg-save-defaults"))
;(gimp-image-get-parasite-list 1) returns number of parasites and string array of currently attached parasites for image id ie (5 ("jpeg-save-options" "jpeg-settings" "exif-data" "gimp-comment" "gimp-metadata"))
;(gimp-file-save RUN-INTERACTIVE image drawable filename raw_filename) this proceedure calls the save by filetype proceedure

; saved to home/gimp-2.8/scripts
; changed location to dmkonlinux's
; 17/01/2015 added set default colours and swap colours and launch web export window
; 27/08/2017 changed to file-jpeg-save from downloaded c plugin gimp-save-for-web
; 27/08/2017 added 2nd file size for alternative image
; 22/10/2018 little tidy up for photography se answer

Este script es muy tosco y está listo, está muy comentado para mi propio beneficio, ya que posiblemente sea solo el segundo script de esquema que he escrito (o que podría escribir). Sin embargo, debería permitir que cualquiera lo adapte con relativa facilidad. Está escrito en linux ubuntu, por lo que la referencia para el directorio de guardado de archivos necesita atención para otros usuarios y, obviamente, la resolución del archivo de salida debe modificarse para satisfacer sus necesidades.

Gracias dmkonlinux. Esto suena como el tipo de cosa que estoy buscando. ¿Estaría dispuesto a compartir su código?
@NatAes He agregado el código (a riesgo de molestar a la policía fuera del tema), espero que ayude.

Hay varias maneras diferentes de hacer esto. Lo más fácil sería recortar las imágenes para hacerlas cuadradas (en Photoshop, esto se puede hacer fácilmente dando a la herramienta de recorte una proporción de lado específica). Pero este es el método obvio y no creo que quieras perder nada de tus imágenes.

La forma que describe se puede lograr en Photoshop creando una nueva imagen en el tamaño correcto, con la relación lateral correcta y el color de fondo correcto (es decir, blanco) y luego simplemente agregue la foto que desea usar en esta imagen y cambie su tamaño a encajar en este nuevo marco. Para asegurarse de que el original no se distorsione, puede bloquear la proporción lateral con el símbolo de candado en la barra de herramientas.

Si tiene que hacer esto para muchas imágenes y porque siempre está haciendo los mismos pasos, también puede automatizar esto con Photoshop con acciones.