prashantwosti
prashantwosti

Reputation: 1010

Fit imported image in panel

I tried importing image via JFileChooser into JPanel. It worked. but I need to fit the image inside the panel without losing its aspect ratio or its proportion.

I tried rescaling the image, here's my code:

Image img = Toolkit.getDefaultToolkit().createImage(picture.getSource());
Image scaledImage = img.getScaledInstance(jPanel1.getWidth(),jPanel1.getHeight(),Image.SCALE_SMOOTH);

g2.drawImage(scaledImage, 0, 0,null,null);

But unable to protect its ratio. I need a simple code for this.

Upvotes: 2

Views: 547

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168845

Try reading the instructions:

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.

Upvotes: 5

Related Questions