Thumbnail image scaling with Java

This tutorial offers example code for a problem we had recently: The automated scaling of images (in our case uploaded via REST Webservice) into thumbnails of different resolutions. Once uploaded, the original image is scaled into different resolutions to provide fitting images for profile, chat or miscellaneous pictures in a web application.

The example code is available as a Maven project on Github.

The scaling is done by the imgscalr library and we added some code in order to scale as many different images or thumbnails as required by the front end web application.


– Maven
– JDK7

If you never used Maven before, check out this tutorial for installation advice.

Thumbnail generation code step-by-step

Starting off with the simplest class, a normal POJO that contains the width, the height or the final pixel size of the desired thumbnails.

This POJO (Plain Old Java Object) class is generated by a “Smart” Enum in our code example. In this Enum we define all the thumbnail resolutions to scale the original image to. This is the only place in the code we have to adapt if we want to add or remove different resolutions.

The actual scaling is done by the ImageScaler class which uses exactly one method of the imgscalr library.
We iterate over the values of Enum and retrieve the ImageResolution POJO which contains the defined resolution or pixels for one single Enum member.

The Scalr.resize() method has multiple parameters to manipulate the scaling process. You can set different qualities (balanced, ultra quality, speed etc.) and modes to fit the image exactly, fit to parameterized width or height or to match exactly. Furthermore you can set the operation mode (last parameter) to antialising, brighter, darker or greyscale. All these parameters affect the speed and result of the scaling process.

Finally we run and test the code via the main class.

The current version in the Git repository took about 5 seconds for a 35 MB image on the local development computer. That sounds like a long time, but the image is pretty big. The speed improves a lot with smaller images.

If you have questions or problems, feel free to ask or comment.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.