2

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
prashantwosti
  • 980
  • 2
  • 7
  • 17
  • 1
    You might like to have a read through http://stackoverflow.com/questions/11959758/java-maintaining-aspect-ratio-of-jpanel-background-image/11959928#11959928 and http://stackoverflow.com/questions/12008507/how-to-make-bmp-fills-the-jpanel/12008809#12008809 and http://stackoverflow.com/questions/12485435/scalable-images-in-java/12486410#12486410 all of which discuss image resizing while maintain the aspect ratio and the perils of the `getSclaedInstance` method – MadProgrammer Oct 02 '12 at 09:38

1 Answers1

5

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433