Scaling Images with Groovy

03 March 2008 ~ blog java groovy

I had the need to scale some large JPG images from my camera so I whipped up a quick little
Groovy script to do the trick.

// groovy ScaleImages.groovy DIRNAME SCALE%
import javax.imageio.ImageIO
import java.awt.Image
import java.awt.Color
import java.awt.image.BufferedImage

class ScaleImages {

    static void main(String[] args){
        def directory = new File(args[0])
            println 'You must specify a valid directory!'

        def scale = Integer.valueOf(args[1])

        directory.eachFile {
            def image =
            int w = image.getWidth() * scale / 100
            int h = image.getHeight() * scale / 100

            def scaled = image.getScaledInstance(w,h,Image.SCALE_SMOOTH)

            def newImage = new BufferedImage(w,h,image.getType())
            def graphics = newImage.createGraphics()

            if(ImageIO.write(newImage,"jpg",new File(it.getParent(),"scaled_${}"))){
                println "scaled: $it"
            } else {
                println "failed: $it"

It's pretty simple. You load the image file to create a BufferedImage. You then create a scaled
Image and draw it onto the new empty BufferedImage and save it off. I would recommend some performance
enhancements if you are doing huge batches of images but for a directory containing a handful of images it works great
and pretty fast. Also, note that this does not handle sub-directories of images, only the directory that you give it.

Creative Commons License content is copyright © 2016 Christopher J. Stehno and available under a Creative Commons Attribution-ShareAlike 4.0 International License.