Java:使用WritableRaster.setRect来叠加图像?

时间:2009-04-20 18:33:02

标签: java image image-manipulation raster

我一直在玩Java中的一些成像功能,试图将一个图像叠加到另一个上。像这样:

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

基本上,我试图叠加这个:https://upload.wikimedia.org/wikipedia/commons/e/e2/Sunflower_as_gif_small.gif
flower
对此:https://www.google.com/intl/en_ALL/images/logo.gif
alt text

产品显示为:http://imgur.com/xnpfp.png
crappy image

从我看到的例子来看,这似乎是合适的方法。我错过了一步吗?有没有更好的方法来处理这个?感谢您的回复。

1 个答案:

答案 0 :(得分:1)

似乎我是以错误的方式解决这个问题。 Sun forums上概述的此解决方案完美无缺(在此处复制):

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