Batch XCF to Jpg Conversion

05/24/2024, Fri
Categories: #shell

Gimp's Default Editing Format to JPG

When saving multiple edited images into Gimp's native image editing format, there will be a need to export them to a readily used format such as JPG. By using the bash script written by Eli you can achieve this task.

However, his bash script requires you to place that file into the same directory as to where the xcf files are located for conversion, which can be improved if you wish to operate on multiple folders with xcf, it would be inconvenient to copy the script to all those folders.

Modifying the script, we have the following file, "convert_xcf_to_jpg.sh", which can take an input and output directories to control where the conversion will take place without the restriction of leaving the script in the same directory as the xcf files.

#!/bin/bash

# Convert xcf to jpg files
# with custom directories for input and output using -i and -o

# Initialize variables
input=""
output=""

# Process options
while getopts ":i:o:" opt; do
  case ${opt} in
  i) input="$OPTARG" ;;
  o) output="$OPTARG" ;;
  \?)
    echo "Invalid option: -$OPTARG" >&2
    Help
    ;;
  :)
    echo "Option -$OPTARG requires an argument." >&2
    Help
    ;;
  esac
done

# Check if both required options are provided
if [[ -z "$input" || -z "$output" ]]; then
  echo "Error: Both -i and -o options are required."
  exit 1
fi

{
  cat <<EOF
(define (convert-xcf-to-jpeg filename outfile)
  (let* (
	 (image (car (gimp-file-load RUN-NONINTERACTIVE filename filename)))
	 (drawable (car (gimp-image-merge-visible-layers image CLIP-TO-IMAGE)))
	 )
    (file-jpeg-save RUN-NONINTERACTIVE image drawable outfile outfile .9 0 0 0 " " 0 1 0 1)
    (gimp-image-delete image) ; ... or the memory will explode
    )
  )

(gimp-message-set-handler 1) ; Messages to standard output
EOF

  # Process the files
  for i in "$input"/*.xcf; do
    filename_without_ext="${i##*/}"
    filename="${filename_without_ext%.*}"
    echo "(gimp-message \"$i\")"
    echo "(convert-xcf-to-jpeg \"$i\" \"${output}$filename.jpg\")"
  done

  echo "(gimp-quit 0)"
} | gimp -i -b -

The following command will take in xcf files from the "xcf" folder and output the files into the "converted" folder:

./convert_xcf_to_jpg.sh -i ./xcf/ -o ./converted/

In a revision of his post, he did recommend that we use the convert command which is provided through Imagemagick, but this didn't work for me. There was an error about memory allocation that came up.

convert Untitled.xcf this.jpg
convert-im6.q16: memory allocation failed `Untitled.xcf' @ error/xcf.c/ReadXCFImage/1363.