Last Updated: February 25, 2016
·
1.607K
· sksamuel

Scala thumbnails

Ever needed to quickly resize an image, maybe to make a thumbnail for some webapp or other? It's quite a common operation, used by any kind of social network, or ecommerce site.

Those from a Java background will remember that this task, whilst not a complicated one, did require an annoying amount of boilerplate, and unless your memory is like an elephant, a trip to google to find the exact steps.

Usually something along the lines of

BufferedImage original = ...
BufferedImage tmp = new BufferedImage(w, h, type); 
Graphics2D g2 = tmp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
g2.drawImage(original, 0, 0, w, h, null);
g2.dispose();

Then what about if we want to fit the image into a certain canvas size, whilst keeping aspect ratio. These kinds of common operations should have been solved years ago.

Enter scrimage. A Scala library for image processing.

Now we can do this

val image = Image(someInputStreamOrFile)
val thumbnail = image.scaleTo(160,120)

And that's it. There are many operations available on the Image instance. See the project for more details. https://github.com/sksamuel/scrimage