Java Graphics How to - Colorize a picture








Question

We would like to know how to colorize a picture.

Answer

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.net.URL;
/*from  w w w . j  a  v a2  s.co  m*/
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Main {
  public static void main(String args[]) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        try {
          JFrame f = new JFrame();
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

          BufferedImage image = ImageIO.read(new URL("http://www.java2s.com/style/download.png"));
          f.getContentPane().add(new JLabel(new ImageIcon(dye(image, new Color(255, 0, 0, 128)))));
          f.pack();
          f.setVisible(true);

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });

  }

  private static BufferedImage dye(BufferedImage image, Color color) {
    int w = image.getWidth();
    int h = image.getHeight();
    BufferedImage dyed = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = dyed.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.setComposite(AlphaComposite.SrcAtop);
    g.setColor(color);
    g.fillRect(0, 0, w, h);
    g.dispose();
    return dyed;
  }

}