Toni Michel Caubet
Toni Michel Caubet

Reputation: 20183

How to use ImageMagick convert command for all images in subfolders

For single files, I am using the following ImageMagick commands (as google suggests):

For png

convert file.png -sampling-factor 4:2:0 -strip -quality 85 -interlace PNG -colorspace sRGB file.png

For jpg

convert file.jpg -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace sRGB file.jpg

But I need to do the same for all .jpg in a subfolder

I tried this:

find ./*.jpg | xargs convert $ -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace sRGB $

And all the images where compressed but named with the name of the first one with an added index, example:

/img/first-one-0.jpg  
/img/first-one-1.jpg  
/img/first-one-2.jpg  
/img/first-one-3.jpg  
...

How could I do It in bulk overriding originals? Even if we have multiple sub-dirs:

/img/dir-1/one.jpg  
...  
/img/dir-2/foo.jpg  

Upvotes: 5

Views: 6076

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 208077

If you want to overwrite all the files in a directory, use mogrify:

mogrify -sampling-factor 4:2:0 -strip -quality 85 -interlace PNG -colorspace sRGB *.png

If you want the results written in a new sub-directory called processed:

mkdir processed
mogrify -path processed ...

If you are on ImageMagick v7 or newer, that becomes:

mkdir processed
magick mogrify -path processed ...

Upvotes: 8

Kinght 金
Kinght 金

Reputation: 18341

Try this:

(1) Save as cvt.py

(2) Open terminal, run python3 cvt.py your_images_root_path


Notice: The following code may modify your images in place, test it first.

#!/usr/bin/python3
# 2018/05/15 20:30:52
# 2018/05/15 20:41:04

## save as cvt.py
## run `python3 cvt.py your_images_root_path` in Terminal


import os
import sys 

def convert(fname): 
    _, ext = os.path.split(fname)
    ext = ext.upper()
    if ext in (".JPEG", ".JPG"):
        fname = "JPG"
    elif ext == ".PNG":
        fname = "PNG"
    else:
        return 
    cmd =  "convert {fname} -sampling-factor 4:2:0 -strip -quality 85 -interlace {} -colorspace sRGB {fname}".format(fname=fname, fmt=fmt)    
    os.system(cmd)

    ## Debug info 
    print(cmd)


def convert_in_dir(root_dir):
    assert os.path.exists(root_dir)
    for dpath, dnames, fnames in os.walk(root_dir):   
        fnames = [os.path.join(dpath, fname) for fname in fnames]
        for fname in fnames:
            convert(fname)

if __name__ == "__main__":
    root_path= sys.argv[1]
    convert_in_dir(root_path)

Upvotes: 0

Related Questions