Gimp Script-Fu: batch-save-as-jpg

This Script-Fu takes a file glob, and a rescaling percentage, and converts the files in the glob to scaled JPG files, flattening all layers.

It is invoked as follows:

gimp-console-2.6.exe -i -b "(batch-save-as-jpg \"z:\\media\\images\\test\\final_xcf\\*.xcf")" -b "(gimp-quit 0)"

(define (batch-save-as-jpg pattern resize)
(let* (
(filelist (cadr (file-glob pattern 1)))
(jpgname "")
(filename "")
(image 0)
(newimage 0)
(drawable 0)
(x1 0)
(x2 0)
(y1 0)
(y2 0)
(width 0)
(height 0)
(selection-bounds 0)

(gimp-message-set-handler 2)
(gimp-message "Preparing to act on the following files")
(gimp-message pattern)

(while (pair? filelist)

; set filename to the name of the current file in the glob
(set! filename (car filelist))
(gimp-message "The current file is: ")
(gimp-message filename)

; set jpgname by tokenizing on "." and taking everything but the last part
(set! fileparts (strbreakup filename "."))
(set! fileparts (butlast fileparts))
(set! jpgname (string-append (unbreakupstr fileparts ".") ".jpg"))
(gimp-message "The new filename will be: ")
(gimp-message jpgname)

; set image from the file, and then get the first layer and set it to newimage
(gimp-message "Loading File.")
(set! newimage (car (gimp-file-load RUN-NONINTERACTIVE filename filename)))

; scale the image
(gimp-message "Scaling the Image.")
; From the Resize %, calculate the new coordinates

; Select all so we can calculate the image size
(gimp-selection-all newimage)

(gimp-message "Getting the Image Size")
; Get the image size and store in x1, x2, y1, and y2
(set! selection-bounds (gimp-selection-bounds newimage))
(set! x1 (cadr selection-bounds))
(set! y1 (caddr selection-bounds))
(set! x2 (- (cadr (cddr selection-bounds)) x1))
(set! y2 (- (caddr (cddr selection-bounds)) y1))

; De-select the selection
(gimp-selection-none newimage)

(gimp-message "Calculating the new width and height.")
; Calculate the image width, height
(set! width (- x2 x1))
(set! height (- y2 y1))

(set! width (* width resize))
(set! height (* height resize))

(set! width (/ width 100))
(set! height (/ height 100))

(gimp-message "The new width is: ")
(gimp-message (number->string width))

(gimp-message "The new height is: ")
(gimp-message (number->string height))

; set drawable to the newimage
(gimp-message "Setting the Drawable.")
(set! drawable (car (gimp-image-flatten newimage)))

; Scale the image to the new width and height
(gimp-drawable-transform-scale drawable 0 0 width height 0 2 0 3 0)
; Crop the image down to the new scaled size
(gimp-image-crop newimage width height 0 0)
; Re-display the cropped image

; Remove any existing selections
(gimp-selection-none newimage)

; save the drawable from newimage as jpgname
(gimp-message "Saving the new file.")
(gimp-file-save RUN-NONINTERACTIVE newimage drawable jpgname jpgname)

(gimp-image-delete newimage)

(set! filelist (cdr filelist))


No comments:

Post a Comment