Search code examples
javaimageaspect-ratiomaximize

How to resize image to maximize their dimensions into a panel without changing aspect ratio


I want to draw some images into a panel, I need that the images conserves their aspect ratio with the biggest dimensions to be drawn over a panel. So given the panel dimensions I must create a Java code to maximize that dimensions. The only ideas that I had needed to solve some linear programming, and I don't know how to do it in Java. Which should be the easiest way to do what I need?


Solution

  • Here is the method to get a re-sized BufferedImage.

    private BufferedImage resizeImage(BufferedImage originalImage, int width, int height)
            throws IOException {
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, width, height, null);
        g.dispose();
        return resizedImage;
    }