Skip to content
Advertisement

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

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.

Advertisement

Answer

Try this code:

JavaScript

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement