1

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.

Haris
  • 13
  • 5
  • https://stackoverflow.com/questions/17271812/save-buffered-image-with-transparent-background ? – k-wasilewski Jul 11 '20 at 17:16
  • Does this answer your question? [Save buffered image with transparent background](https://stackoverflow.com/questions/17271812/save-buffered-image-with-transparent-background) – Umutambyi Gad Jul 11 '20 at 17:22

1 Answers1

4

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.

JCWasmx86
  • 3,473
  • 2
  • 11
  • 29
  • Good answer.  A Kotlin version would be very similar.  (Of course, in either case, for production code you'd probably pass in the new size instead of hard-coding, copy the existing image's type, calculate where to draw the existing image within the new one, and maybe do a little error trapping too.  But I'm sure OP realises that!  This answer shows the essentials well.) – gidds Jul 11 '20 at 18:19
  • Thank you very much. It works perfectly with a little editing – Haris Jul 11 '20 at 22:46