Compressing JPG Images with Groovy

how-to
Nov 26, 20113 mins

I recently had need to reduce the size of a large number of JPG images. I did not want to do this one at a time in a graphics manipulation tool, so scripting seemed like the obvious choice. These days, Groovy is my generally my preferred tool for scripting jobs. I noted that Eric Wendelin had posted Crush images on the command-line with Groovy that demonstrates using Groovy in conjunction with ImageMagick to “[compress] images the Groovy way.” This looks like an easy and attractive way to do it, but it requires ImageMagick and, if on Windows, Cygwin. I decided to write a similar script using straight Java and Groovy to see if I could reduce required dependencies. Note that this script would have been more concise had I used the Java Advanced Imaging API, but that would have meant another separate dependency.

rescaleJpgImage.groovy

import java.awt.Image
import java.awt.image.BufferedImage
import java.awt.image.RenderedImage
import javax.imageio.IIOImage
import javax.imageio.ImageIO
import javax.imageio.ImageWriteParam
import javax.imageio.ImageWriter
import javax.imageio.stream.FileImageOutputStream

if (args.length < 2)
{
   println "USAGE: groovy rescaleImage.groovy <sourceDirectory> <scalingFactor>n"
   println "twhere <sourceDirectory> is directory from which image files come"
   println "t      <scalingFactor> is scaling factor for reduced image (0 to 1)"
   System.exit(-1)
}

def directoryPath = args[0]
def directory = new File(directoryPath)
if (!directory.isDirectory())
{
   println "${directoryPath} is NOT an existing directory!"
   System.exit(-1)
}

def scaleFactor = args[1] as float
def iter = ImageIO.getImageWritersByFormatName("jpeg")
def writer = (ImageWriter)iter.next()
def imageWriteParameters = writer.getDefaultWriteParam()
imageWriteParameters.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imageWriteParameters.setCompressionQuality(scaleFactor);

def backupDirName = "backup_" + System.currentTimeMillis()
def targetDirectory = new File(backupDirName)
targetDirectory.mkdir()
def targetDirectoryPath = targetDirectory.canonicalPath
directory.eachFile
{ file ->
   def fullFileName = file.canonicalPath
   def fileName = file.name
   def sourceImage = ImageIO.read(new File(fullFileName))
   def targetName = targetDirectoryPath + File.separator + fileName
   println "Copying ${fullFileName} to ${targetName} with scale factor of ${scaleFactor} ..."
   def targetFile = new File(targetName);
   def output = new FileImageOutputStream(targetFile);
   writer.setOutput(output);
   def image = new IIOImage(sourceImage, null, null);
   writer.write(null, image, imageWriteParameters);
}
writer.dispose();

The Groovy script above does not change the input image files, but instead re-writes them with the same name to a new directory. The new directory is named by concatenating the milliseconds since epoch time after “backup_”. The files are written as JPG files and are scaled by the provided scaling factor.

This script was sufficient for my needs, but there are many ways it could be improved. Groovy’s built-in CLI-based command-line support could be used for nicer handling of command-line options. There could be better checks to verify that the provided scaling factor is a numeral between 0 and 1. Using libraries such as Java Advanced Imaging API, ImageMagick, or imgscalr might have made the script even more concise.

Conclusion

This is another example of how Groovy combines the best of scripting with the feature-rich libraries of Java. The above script could have been written in Java, but Groovy seems a better fit for scripts like this one.

Original posting available at https://marxsoftware.blogspot.com/ (Inspired by Actual Events)