Search code examples
batch-processinggimpscript-fu

GIMP Script.Fu script to batch convert JPEG to PNG


Can someone give me the script I would need to run to batch convert many *.jpeg files to *.png in Script.Fu in GIMP?

Currently I am spending way too much time manually exporting every image and it's a waste of time.

I can't install anything right now so can't use alternative applications.


Solution

  • Alright, after a lot of trials and errors I finally figured out how to convert one file format to another using only GIMP.

    This is the Script-Fu script for conversion to PNG:

    (
        let* ((filename "{{filename}}")
                (output "{{output}}")
                (image (car (gimp-file-load 1 filename filename)))
                (drawable (car (gimp-image-get-active-layer image))))
        (file-png-save-defaults 1 image drawable output output)
    )
    

    Where {{filename}} is input file that needs to be converted (a jpeg file, for example), {{output}} is the output file that you need (it can be simply the same file name but with PNG extension)

    How to run it: it can probably be improved

    gimp -i -n -f -d --batch "{{one-line script-fu}}"
    

    More about command line options you can find in GIMP online documentation.

    The place that needs to be changed is {{one-line script-fu}} and it has to be... one-line! You can probably do all of this in one file using cmd (in case if you use Windows), but for me it was easier to use Python, so here's the script for it:

    import subprocess, os
    
    def convert_to_png(file_dds):
        #Loads the command to run gimp cli (second code block)
        #Note: remove "{{one-line script-fu}}" and leave one space after the --batch
        with open("gimp-convert.bat", "r") as f:
            main_script = f.read()
    
        #Prepares the Script-Fu script to be run, replacing necessary file names and makes it one-line (the firs code block)
        with open("gimp-convert-png.fu", "r") as f:
            script = f.read().replace("\n", " ").replace("{{filename}}", file_dds) \
                .replace("{{output}}", file_dds[:-3]+"PNG").replace("\\", "\\\\").replace("\"", "\\\"")
    
        subprocess.run(main_script + " \"" + script + "\" --batch \"(gimp-quit 1)\"",
            cwd = os.getcwd(),
            shell = True)
    

    And you should get your file converted to PNG!

    I needed this for my texture upscale project, all of the code below you can find here.

    Tested with GIMP 2.10