Автоматическое пакетное изменение размера изображений путем добавления пустого пространства (т. е. без искажения исходных пропорций)

У меня есть несколько фотографий, каждая из которых разного размера и разрешения. Я хотел бы сделать их все квадратными - разрешение не критично и может различаться по фотографиям, но каждое выходное изображение должно быть пропорционально квадратным.

Мне также нужно убедиться, что исходная фотография не искажена и не перекошена каким-либо образом — я предполагаю, что это можно сделать, добавив пустое пространство внизу горизонтальной прямоугольной фотографии (например), но могут быть и другие способы добиться этого. ...

Любая помощь будет здорово!

Спасибо

Ответы (3)

Вы можете использовать ImageMagick, чтобы изменить размер изображения и поместить его на холст большего размера с белым фоном. Если вы используете Mac или Linux, вы можете обрабатывать файлы в цикле for:

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

Вы можете использовать parallelдля обработки нескольких файлов одновременно:

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

Я сделал что-то подобное, чтобы создать изображения точно такого же размера для слайд-шоу html, даже если исходный файл был обрезан или имел книжную или альбомную ориентацию. Я использовал gimp и сценарий схемы, чтобы упростить процесс, поскольку эти различия в размере и соотношении входных данных усложняли процесс. Я не полностью автоматизировал это, так как я делал только пять картинок за раз, и я очень начинающий самоучка в кодировании. Тем не менее, это заняло чуть более сотни строк кода.
Процесс был примерно следующим:

  1. Если ширина входного изображения больше высоты, масштабируйте изображение до целевой ширины на исходную высоту x (исходная ширина/целевая ширина). В качестве альтернативы целевая высота по исходной ширине x (исходная высота / целевая высота).
  2. Измените размер холста на целевую ширину на целевую высоту со смещениями по центру.
  3. Свести и сохранить файл.

листинг кодов

;; -*-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

Этот сценарий очень грубый и готовый, он сильно прокомментирован для моей же пользы, так как это, возможно, только второй сценарий схемы, который я написал (или когда-либо) написал. Тем не менее, это должно позволить любому адаптировать его относительно легко. Он написан на linux ubuntu, поэтому ссылка на каталог сохранения файлов требует внимания других пользователей, и, очевидно, разрешение выходного файла необходимо изменить в соответствии с вашими потребностями.

Спасибо дмконлинукс. Это похоже на то, что я ищу - не могли бы вы поделиться своим кодом?
@NatAes Я добавил код (рискуя расстроить полицию, не относящуюся к теме), надеюсь, это поможет.

Есть несколько разных способов сделать это. Проще всего было бы обрезать изображения, чтобы сделать их квадратными (в Photoshop это можно легко сделать, задав инструменту кадрирования заданное соотношение сторон). Но это очевидный метод, и я не думаю, что вы хотите что-то потерять из своих изображений.

Способ, который вы описываете, может быть достигнут в Photoshop путем создания нового изображения правильного размера, с правильным соотношением сторон и правильным цветом фона (например, белым), а затем просто добавьте фотографию, которую вы хотите использовать в этом изображении, и измените ее размер на вписаться в эту новую рамку. Чтобы убедиться, что оригинал не искажен, вы можете зафиксировать соотношение сторон с помощью символа блокировки на панели инструментов.

Если вам нужно сделать это для большого количества изображений и потому что вы всегда делаете одни и те же шаги, вы также можете автоматизировать это с помощью Photoshop с действиями.