How can I resize a rectangular image to a square image while maintaining aspect ratio in Java?

Tags: , , ,

I need to resize rectangular images (400×600) into square images (600×600) while keeping aspect ratio of the original image. The newly added pixels need to be transparent. Like this.

I need it in java or kotlin code. But if that’s not possible then I don’t mind a solution in any other language.

I have not been able to find a suitable solution for the last 3 days. All similar questions have not helped at all because they deal with either up-scaling or down-scaling both height and width while maintaining aspect ratio. I need to increase the width only.


Try this code:

public static BufferedImage increaseSize(BufferedImage input){
    //TODO: Maybe validate the input.
    //Create a new image of 600*600 pixels
    BufferedImage output=new BufferedImage(600,600,BufferedImage.TYPE_4BYTE_ABGR);
    //Get the graphics object to draw onto the image
    Graphics g=output.getGraphics();
    //This is a transparent color
    Color transparent=new Color(0f,0f,0f,0f);
    //Set the transparent color as drawing color
    //Make the whole image transparent
    //Draw the input image at P(100/0), so there are transparent margins
    //Release the Graphics object
    //Return the 600*600 image
    return output;

Here, an example: Example On the left you can see the image before, after the conversion you can see the effect on the right.

Source: stackoverflow