resize image to fixed size, add border if needed

java

Solution

Kris,

You can give imgscalr a try; it implements the most optimized method for scaling images in Java and also (by default) honors the orientation and proportions of the original image when resizing... it also provides a very handy pad(...) operation that will give you the border you want.

The only thing it won't do for you is auto-pad the difference between the scaled picture and a perfectly square 500x500 size but you can scale the image to something like 498x498 -- it will give you a proportional result fitting the primary dimension (horz or port depending on orientation) and then you can pad(2) to give it a nice border with any color you want including a transparent one.

For example, the code would look something like this (using static imports for readability):

import org.imgscalr.Scalr.*;
import java.awt.Color;

public static BufferedImage createThumbnail(BufferedImage img) {
    // Target width of 500x500 is used
    img = resize(img, 500); 
    return pad(img, 2, Color.BLACK);
}

The resize() method takes any number of additional arguments for adjusting fitting behavior, image quality, speed-of-operation, etc.

You can also apply any of the pre-defined OPs on the resulting image before returning it (here) by passing it as the last arg to resize or pad (or any of the other operations).

Additionally if you are trying to do this in a server process and want to run these ops asynchronously, you can look at the AsyncScalr class which offers all the same functions, but queues the operations up against a configurable number of scaling threads to avoid saturating the host machine.

imgscalr has been deployed in a number of server and client scenarios in production over the last few years. I'd love to hear your feedback if you get a chance to try out the library.

Problem

I need to make images I downloaded from flickr to fit into a 500x500 shape. If the aspect ratio is not 1:1 than black bars should be added to top / bottom or left / right to fill empty space. Transparent background could also work. Important is 500x500 and resizing without cropping. how can I do it in java?

Original source