How do I merge two image files ? I'm trying to create a watermark on a document image.

Curtis Hatter

I do not exactly how watermarks are done but I can tell you how to merge to pictures together. Here's the code first, It's a simple program I wrote up to demonstrate transparency:

public class TransparentImage
       extends JFrame {
    BufferedImage bi1;
    BufferedImage bi2;
    public static void main(String args[]) {
        TransparentImage ti = new TransparentImage( );
        ti.setSize(400, 400);

    public TransparentImage( ) {
        Image image1 = Toolkit.getDefaultToolkit().getImage("duke.gif");
        Image image2 = Toolkit.getDefaultToolkit().getImage("SunLogo.gif");
        MediaTracker tracker = new MediaTracker(this);
        tracker.addImage(image1, 0);
        tracker.addImage(image2, 0);
        try { 
            tracker.waitForID(0); }
        catch (InterruptedException ie) {
            ie.printStackTrace( ); }
        bi1 = new BufferedImage(image1.getWidth(null), image1.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = bi1.createGraphics( );
        g2.drawImage(image1, null, null);
        bi2 = new BufferedImage(image2.getWidth(null), image2.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        g2 = bi2.createGraphics( );
        g2.drawImage(image2, null, null);

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        Point2D center =  new Point2D.Float(this.getHeight( ) / 2, this.getWidth( ) / 2);
        AffineTransform at = AffineTransform.getTranslateInstance(center.getX( ) - (bi2.getWidth( ) / 2), center.getY( ) - (bi2.getHeight( ) / 2));
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.drawImage(bi2, 0, 0, null);
        Composite c = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .35f);
        at = AffineTransform.getTranslateInstance(center.getX( ) - (bi1.getWidth( ) / 2), center.getY( ) - (bi1.getHeight( ) / 2));
        g2.drawImage(bi1, 0, 0, null);

The above code loads in 2 images (which you should be able to find in the jdk directory somewhere. Then paints them on the screen. Some of the stuff is just used to align them in the center so that you can see how the transparency works.

The major part for you to be interested in is the Composite class. That's what allows you to merge the two images together. The Composite class defines several compositing methods you can use. With most being the Porter-Duff rules.

Once you create your compositing rule then apply to the graphics context and then draw the image you want composited. That's all there is to it.