1

我想在灰色阴影图像上重叠包含一些白点的黑色图像。我想让这个黑色图像透明。我使用了这里提到的 Java 代码。

但输出显示红色图像。为什么?

代码在这里提到:

    public class OverlayImage{
        public static void main(String[] args) {
            File path = new File("/home/dmdd/Desktop/images"); // base path of the images

            // load source images
            BufferedImage image=null;
            BufferedImage overlay=null;
            try {
                image = ImageIO.read(new File(path, "image.jpg"));
                overlay = ImageIO.read(new File(path, "overlay.jpg"));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //overlay =(BufferedImage) makeImageTransparent(overlay,50);
            OverlayImage over=new OverlayImage();
            // create the new image, canvas size is the max. of both image sizes
            int w = Math.max(image.getWidth(), overlay.getWidth());
            int h = Math.max(image.getHeight(), overlay.getHeight());
            //BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

            Image overlay1=over.TransformGrayToTransparency(overlay);
            BufferedImage combined=over.ApplyTransparency(image, overlay1);
            try {
                ImageIO.write(over.toBufferedImage(combined, w, h), "JPG", new File(path, "combined.jpg"));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        private Image TransformGrayToTransparency(BufferedImage image)
        {
            ImageFilter filter = new RGBImageFilter()
            {
                public final int filterRGB(int x, int y, int rgb)
                {
                    return (rgb << 8) & 0xFF000000;
                }
            };

            ImageProducer ip = new FilteredImageSource(image.getSource(), filter);
            return Toolkit.getDefaultToolkit().createImage(ip);
        }

        private BufferedImage ApplyTransparency(BufferedImage image, Image mask)
        {
            BufferedImage dest = new BufferedImage(
                    image.getWidth(), image.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = dest.createGraphics();
            g2.drawImage(image, 0, 0, null);
            AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.DST_IN, 1.0F);
            g2.setComposite(ac);
            g2.drawImage(mask, 0, 0, null);
            g2.dispose();
            return dest;
        }
}

白点图像是: 在此处输入图像描述

黑色图像是: 在此处输入图像描述

叠加的红色图像是: 在此处输入图像描述

4

1 回答 1

2

You are trying to save the resulting image as a jpeg. The resulting image contains the alpha / transparency level, while jpeg images don't support transparency. Save it as a png image.

于 2012-10-01T11:26:40.923 回答