Java Graphics How to - Reset image by color








Question

We would like to know how to reset image by color.

Answer

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.net.URL;
/*from   w w w .jav  a2s.c  o m*/
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class Main {

  public static BufferedImage getTransparentImage(BufferedImage image,
      Color transparent) {
    BufferedImage img = new BufferedImage(image.getWidth(), image.getHeight(),
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = img.createGraphics();
    for (int x = 0; x < img.getWidth(); x++) {
      for (int y = 0; y < img.getHeight(); y++) {
        if (image.getRGB(x, y) != transparent.getRGB()) {
          img.setRGB(x, y, image.getRGB(x, y));
        }
      }
    }
    g.dispose();
    return img;
  }

  public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.java2s.com/style/download.png");
    final BufferedImage trans = getTransparentImage(ImageIO.read(url),
        Color.BLACK);
    Runnable r = new Runnable() {
      @Override
      public void run() {
        JLabel gui = new JLabel(new ImageIcon(trans));
        JOptionPane.showMessageDialog(null, gui);
      }
    };
    SwingUtilities.invokeLater(r);
  }
}