-1

How do you rezize an ImageIcon?

Let´s say we have a ImageIcon we want to display on a screen. But the ImageIcon is too big so we cannot see the whole picture. Then it would be desirable to be able to rezize the ImageIcon to a specific width and height, with the intention of making the displayed ImageIcon smaller so we can see the whole image on the screen. Any idea how this could be done in java?

camickr
  • 321,443
  • 19
  • 166
  • 288
Isus
  • 143
  • 2
  • 16
  • Let's imagine you had access to the largest repository of knowlegde and tried, maybe [Googling](https://www.google.com.au/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=java+resize+imageicon&*) or even [StackOverflow](http://stackoverflow.com/search?q=%5Bjava%5D+resize+imageicon), just imagine what you might have achieved in that time – MadProgrammer Mar 11 '17 at 22:27
  • @UnholySheep I tried using `getScaledInstance()` method, but that method would only work for the type Image, not ImageIcon. I then tried to convert my ImageIcon to a Image-object but Eclipse said "Cannot cast from ImageIcon to Image" – Isus Mar 12 '17 at 08:49
  • @UnholySheep I then tried using something along with this: `public static BufferedImage resize(BufferedImage image, int width, int height) { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT); Graphics2D g2d = (Graphics2D) bi.createGraphics(); g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)); g2d.drawImage(image, 0, 0, width, height, null); g2d.dispose(); return bi; }` Tried adjusting the method to fit ImageIcon, but encountered the same problem as in my comment above. – Isus Mar 12 '17 at 08:51
  • @UnholySheep The solution above seemed (to me) more far fetched than the `getScaledInstance()` method, so I tried again with that. Succeeded in converting ImageIcon to a Icon by making this: `Image image = (Image) imageIcon.getImage();` then using `getScaledInstance()` on `image`. Then I tried adding the image to a JLabel but that would not accept the object type of `image` (which was of the object type Image). Then tried converting `image` back to a ImageIcon which would not work... So now I am back at square one again – Isus Mar 12 '17 at 09:16

1 Answers1

1

You can use Image.getScaledInstance(...) to resize the Image to your desired fixed size. Then you create your ImageIcon and add it to a JLabel.

You can read up on The Perils of Image.getScaledInstance() blog for more information and other suggestions.

You can also try using the Stretch Icon. This Icon will dynamically resize itself based on the space available to the JLabel.

camickr
  • 321,443
  • 19
  • 166
  • 288