user2801078
user2801078

Reputation:

Convert imagicon to image

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?

Upvotes: 0

Views: 179

Answers (1)

durron597
durron597

Reputation: 32323

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;
}

Upvotes: 2

Related Questions