Search code examples
javaimageresizebufferedimagejava-2d

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));

Solution

  • 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)