Converting an ImageIcon to a BufferedImage
Asked Answered
B

3

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.

Beiderbecke answered 24/2, 2013 at 15:24 Comment(0)
G
41

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();
Gaspard answered 24/2, 2013 at 15:26 Comment(3)
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.Beiderbecke
BufferedImage.TYPE_INT_ARGB if there are transparent pixels in the icon.Toluene
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"?Remittance
P
11

See ImageIcon, Image and BufferedImage:

ImageIcon yourImage;
Image image = yourImage.getImage();
BufferedImage buffered = (BufferedImage) image;
Phonology answered 24/2, 2013 at 15:29 Comment(2)
Use this if the ImageIcon contains a BufferedImage, or Werner's answer otherwise.Hypophyge
That works on Windows but not on Linux (tried on Ubuntu).Toluene
Y
-3

I tried something called Scalr, view the code below

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

Cheers.

Yetty answered 24/2, 2013 at 15:28 Comment(1)
Doesn't answer the OP's question. You're just reading a file, not converting an ImageIcon object to a BufferedImage objectFederalist

© 2022 - 2024 — McMap. All rights reserved.