Wizard Sultan
Wizard Sultan

Reputation: 918

resizing an image without compromising the aspect ratio

I use the following codes to resize an image but the problem is that they don't maintain the original aspect ratio, is there any way by which I can resize the image without compromising the aspect ratio.

BufferedImage img1 = new BufferedImage(800, 600,
                    BufferedImage.TYPE_INT_RGB);
            img1.createGraphics()
                    .drawImage(
                            ImageIO.read(
                                    new File("/home/rvkydmpo/webapps/ROOT/images/profilePicture/"
                                            + fileName)).getScaledInstance(800,
                                    600, Image.SCALE_SMOOTH), 0, 0, null);
            ImageIO.write(img1, "jpg", new File("/home/rvkydmpo/webapps/ROOT/images/profilePicture/" +fileName));

Upvotes: 1

Views: 1333

Answers (2)

ceasaro
ceasaro

Reputation: 615

I don't know on what server you are running your code, but if you running it on linux based system you could use the imagemagick convert command.

There's also a java library available to call imagemaick it called JMagick

Upvotes: 0

user2298374
user2298374

Reputation:

You might want to read the docs of getScaledInstance():

Image java.awt.Image.getScaledInstance(int width, int height, int hints)

Creates a scaled version of this image. A new Image object is returned which will render the image at the specified width and height by default. The new Image object may be loaded asynchronously even if the original source image has already been loaded completely.

If either width or height is a negative number then a value is substituted to maintain the aspect ratio of the original image dimensions. If both width and height are negative, then the original image dimensions are used.

(emphasis mine)

Upvotes: 3

Related Questions