Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I agree this code works, to size an ImageIcon from a file for display while keeping the aspect ratio I have used the below.</p> <pre><code>/* * source File of image, maxHeight pixels of height available, maxWidth pixels of width available * @return an ImageIcon for adding to a label */ public ImageIcon rescaleImage(File source,int maxHeight, int maxWidth) { int newHeight = 0, newWidth = 0; // Variables for the new height and width int priorHeight = 0, priorWidth = 0; BufferedImage image = null; ImageIcon sizeImage; try { image = ImageIO.read(source); // get the image } catch (Exception e) { e.printStackTrace(); System.out.println("Picture upload attempted &amp; failed"); } sizeImage = new ImageIcon(image); if(sizeImage != null) { priorHeight = sizeImage.getIconHeight(); priorWidth = sizeImage.getIconWidth(); } // Calculate the correct new height and width if((float)priorHeight/(float)priorWidth &gt; (float)maxHeight/(float)maxWidth) { newHeight = maxHeight; newWidth = (int)(((float)priorWidth/(float)priorHeight)*(float)newHeight); } else { newWidth = maxWidth; newHeight = (int)(((float)priorHeight/(float)priorWidth)*(float)newWidth); } // Resize the image // 1. Create a new Buffered Image and Graphic2D object BufferedImage resizedImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = resizedImg.createGraphics(); // 2. Use the Graphic object to draw a new image to the image in the buffer g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, newWidth, newHeight, null); g2.dispose(); // 3. Convert the buffered image into an ImageIcon for return return (new ImageIcon(resizedImg)); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload