Inverting the colour of images

Today I was asked by a family member if I could help. They had purchased some hardware that scans in all their photo negatives, which whilst cool, has the unfortunate side-effect of resulting in images with inverted colours. Not exactly what you want to see in the (virtual) photo album!

It turns out that in the last year or so I’ve had a lot to do with image manipulation and editing in Java, so after having a brief look for a tool that they could use to batch invert their photos, I just jumped straight into Java to develop a solution. This was particularly fun as it’s been about six months since I’ve had to cut any Swing/Java2D Java code (I’m fairly fulltime JavaFX these days), so it was nice to just refresh myself after the time away.

The code below is what I ended up writing. There is almost certainly a better way to do it, but this runs perfectly well for the family member, so I didn’t go any further than that. It doesn’t have any dependencies on external libraries, and should probably run on most recent Java releases (probably 1.4+, but possibly even earlier). I’ve only tested it on my Java 6 install however. I thought I’d post it here in case anyone else is interested in batch inverting their images. For those not inclined to compile the code, you can also download the application and run it on your local machine (normally by double clicking on the file).

Warning: This code is certainly not good enough for a proper production system, as all the image processing is taking place within the user interface thread (i.e. on the Event Dispatch Thread as it’s known in Java). I was weary of posting too much code on this blog, and also the wrapping would get even worse than what is seen below. Because of this, if the code below is used in a ‘proper’ application, the user interface will freeze up whilst the images are being inverted. If you want to use this code in a proper application, please be sure to move the ImageIO stuff off onto a separate thread (e.g. by using a SwingWorker). This is very trivial, but if you have any questions please feel free to leave a comment.

Here’s the source code:

3 thoughts on “Inverting the colour of images”

Leave a Reply