Declaration of VAR

and some other stuff

Mac OS service for resizing pictures

2017-03-20 13:15:08 +0100

2017-03-20 13:15:08 +0100 | Comments

So, there is a need to quickly resize some pictures - for example, scale a bunch of photos to width of 800px (preserving the aspect ratio). And of course we want a Mac OS service for that, so we could just right-click selected pictures and do it.

Well, it’s all the same like it was with in the article “Convert video with service in Mac OS”. Basically, the only thing that is different - the main script. And here it is:

on run {input, parameters}
    
    set logScript to load script "/path/to/your/scripts/write2log.scpt"
    set fnameScript to load script "/path/to/your/scripts/getFname.scpt"
    
    set fcount to 0
    
    try # resizing
    
        #repeat with i from 1 to the count of input
        repeat with i in input
            set fname to POSIX path of i
            # [debug]
            #write2log("/path/to/some.log", fname) of logScript
            # filepath without extension
            set fnameWE to getPathWithoutExtension(fname) of fnameScript
            # extension
            set fext to getExtension(fname) of fnameScript
            # new file (resized picture)
            set new_fname to fnameWE & "_w800." & fext
            # [debug]
            #write2log("/path/to/some.log", new_fname) of logScript
            do shell script "sips --resampleWidth 800 -s formatOptions high \"" & fname & "\" --out \"" & new_fname & "\""
            set fcount to fcount + 1
        end repeat
    
     on error ex
        write2log("/path/to/some.log", ex) of logScript
        error "failed"
    end try
    
    try # play sound
        set doneSound to quoted form of "/path/to/some/sound.mp3"
        do shell script "afplay " & doneSound
     on error ex
         write2log("/path/to/some.log", ex) of logScript
    end try
    #say "Done"
    #beep
    
    return fcount
end run

And also change the filter for acceptable files to image files:

Another difference from previous version is that I got rid of crutches for getting filename and extension and instead used getExtension() and getPathWithoutExtension() functions.

The core of the resizing process is sips - a CLI-utility for image processing, and option --resampleWidth 800 resizes given pictures to 800px width (preserving the aspect ratio). Option -s formatOptions high controls the quality and that’s the default value, so you can just delete it - result will be the same.

Save the service and that’s it, now it is available in Finder under right-click menu for pictures:

…By the way, you could’ve just used a ready-made script from the Automator library. It gives you the same result (and most probably uses sips utility too), but with my custom service you have control over naming and quality settings, so it was still worth creating it.