0

I need to convert an ImageIcon into an Image for a program how should I go about doing it? I there a method of casting I can use or a built in method to do it?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • possible duplicate of [Converting an ImageIcon to a BufferedImage](http://stackoverflow.com/questions/15053214/converting-an-imageicon-to-a-bufferedimage) – durron597 Sep 21 '13 at 21:42
  • Something other than http://docs.oracle.com/javase/7/docs/api/javax/swing/ImageIcon.html#getImage()? – Mark Elliot Sep 21 '13 at 21:55
  • It's not really the same thing though the bufferedimage –  Sep 21 '13 at 22:59
  • *"I need to convert an ImageIcon into an Image"* This wreaks of 'bad design'. Supposedly you originally had a reference to an image in order to create an icon, so just use the original! – Andrew Thompson Sep 22 '13 at 06:44

1 Answers1

2

Building on the answer from the question I linked. I'm not sure which Image you mean, save it as a file or get a java Image instance, but you can use just the second method if you mean the latter, or use the former (which depends on the latter) if you need that.

// format should be "jpg", "gif", etc.
public void saveIconToFile(ImageIcon icon, String filename, String format) throws IOException {
  BufferedImage image = iconToImage(icon);
  File output = new File(filename);
  ImageIO.write(bufferedImage, format, outputfile);
}

public BufferedImage iconToImage(ImageIcon icon) {
  BufferedImage bi = new BufferedImage(
      icon.getIconWidth(),
      icon.getIconHeight(),
      BufferedImage.TYPE_INT_ARGB);
  Graphics g = bi.createGraphics();

  // paint the Icon to the BufferedImage.
  icon.paintIcon(null, g, 0,0);
  g.dispose();

  return bi;
}
durron597
  • 31,968
  • 17
  • 99
  • 158