12

I've been trying to convert a ImageIcon to BufferedImage... And I've had no luck.

I have a pre-existing ImageIcon that needs to be converted to a Buffered Image for the vast amount of BufferedImage operations that exist.

I have found a few ways, but all of them are hugely CPU intensive.

Caelum
  • 801
  • 2
  • 10
  • 19

3 Answers3

40

What's wrong with:

BufferedImage bi = new BufferedImage(
    icon.getIconWidth(),
    icon.getIconHeight(),
    BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
// paint the Icon to the BufferedImage.
icon.paintIcon(null, g, 0,0);
g.dispose();
Werner Kvalem Vesterås
  • 10,226
  • 5
  • 43
  • 50
  • 1
    Very helpful thank you very much, I had previously came accross this method, but quickly shot it down due to my immiediet assumption that it would perform badly, but after trying it your way, it all seems to work fine. – Caelum Feb 24 '13 at 15:53
  • 3
    `BufferedImage.TYPE_INT_ARGB` if there are transparent pixels in the icon. – Matthieu Feb 23 '17 at 16:47
  • Shouldn't we also do `g.setComposite(AlphaComposite.Src)` before calling `paintIcon` to copy all the transparent pixels as is, not as strictly "transparent black"? – SerVB May 31 '23 at 16:23
10

See ImageIcon, Image and BufferedImage:

ImageIcon yourImage;
Image image = yourImage.getImage();
BufferedImage buffered = (BufferedImage) image;
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
-3

I tried something called Scalr, view the code below

Scalr.resize((BufferedImage) ImageIO.read(file), Method.SPEED, 250, OP_ANTIALIAS, OP_BRIGHTER);

Cheers.

tmwanik
  • 1,643
  • 14
  • 20
  • 1
    Doesn't answer the OP's question. You're just reading a file, not converting an ImageIcon object to a BufferedImage object – Samuël Visser Mar 09 '20 at 09:14