javaimagekotlinrescale

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


I need to resize rectangular images (400x600) into square images (600x600) 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.


Solution

  • 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
        g.setColor(transparent);
        //Make the whole image transparent
        g.fillRect(0,0,600,600);
        //Draw the input image at P(100/0), so there are transparent margins
        g.drawImage(input,100,0,null);
        //Release the Graphics object
        g.dispose();
        //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.