Search code examples
javaimageimage-manipulationraster

Java: using WritableRaster.setRect to superimpose an image?


I have been playing with some of the imaging functionality in Java, trying to superimpose one image over another. Like so:

BufferedImage background = javax.imageio.ImageIO.read(
    new ByteArrayInputStream(getDataFromUrl(
        "https://www.google.com/intl/en_ALL/images/logo.gif"
    ))
);
BufferedImage foreground = javax.imageio.ImageIO.read(
    new ByteArrayInputStream(getDataFromUrl(
        "https://upload.wikimedia.org/wikipedia/commons/e/e2/Sunflower_as_gif_small.gif"
    ))
);

WritableRaster backgroundRaster = background.getRaster();
Raster foregroundRaster = foreground.getRaster();

backgroundRaster.setRect(foregroundRaster);

Basically, I was attempting to superimpose this: https://upload.wikimedia.org/wikipedia/commons/e/e2/Sunflower_as_gif_small.gif
flower
on this: https://www.google.com/intl/en_ALL/images/logo.gif
alt text

The product appears as: https://i.sstatic.net/ep3XE.png
crappy image

From the examples I have seen, this seems to be the appropriate method. Am I missing a step? Is there a better way to handle this? Thank you for your responses.


Solution

  • Seems I was going about this in all the wrong ways. This solution outlined on the Sun forums works perfectly (copied here):

    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    class TwoBecomeOne {
        public static void main(String[] args) throws IOException {
            BufferedImage large = ImageIO.read(new File("images/tiger.jpg"));
            BufferedImage small = ImageIO.read(new File("images/bclynx.jpg"));
            int w = large.getWidth();
            int h = large.getHeight();
            int type = BufferedImage.TYPE_INT_RGB;
            BufferedImage image = new BufferedImage(w, h, type);
            Graphics2D g2 = image.createGraphics();
            g2.drawImage(large, 0, 0, null);
            g2.drawImage(small, 10, 10, null);
            g2.dispose();
            ImageIO.write(image, "jpg", new File("twoInOne.jpg"));
            JOptionPane.showMessageDialog(null, new ImageIcon(image), "",
                                          JOptionPane.PLAIN_MESSAGE);
        }
    }