如何阻止java将我的BufferedImage设置为完全透明?

时间:2014-10-02 21:14:51

标签: java transparency bufferedimage

我正在尝试在java中创建一个图像编辑器,但是当我运行代码时,输​​出图像是完全透明的。

这是我的Main.java代码:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Main {

    public static void main(String[] args) {

        BufferedImage image = null;
        try {
            image = ImageIO.read(new File("strawberry.png"));
        } catch (IOException e) {
            System.out.println(e);
        }

        new Negative(image);

        File outputfile = new File("saved.png");

        try {
            ImageIO.write(image, "png", outputfile);
        } catch (IOException e) {
            System.out.println(e);
        }

    }

}

这是我的Negative.java代码:

import java.awt.image.BufferedImage;

public class Negative {

    public Negative(BufferedImage img) {

          for (int x = 0; x < img.getWidth(); ++x) {
                for (int y = 0; y < img.getHeight(); ++y) {

                    int rgb = img.getRGB(x, y);
                    int r = (rgb >> 16) & 0xFF;
                    int g = (rgb >> 8) & 0xFF;
                    int b = (rgb & 0xFF);

                    r = 255 - r;
                    g = 255 - g;
                    b = 255 - b;

                    int newColour = (r << 16) + (g << 8) + (b << 4); 
                    img.setRGB(x, y, newColour);

                }
          }

    }

}

如果有人可以提供帮助,我将非常感激。

2 个答案:

答案 0 :(得分:2)

问题

他们称之为RGB颜色实际上是ARGB,每个8位。 Alpha以最高8位给出,0表示透明,255表示完全不透明。

这是TYPE_INT_ARGBBufferedImage.setRGB()的javadoc中的含义:

  

假设像素位于默认的RGB颜色模型TYPE_INT_ARGB和默认的sRGB颜色空间中。

解决方案

对于完全不透明的图像,请添加255 alpha值:

int newColour = (0xff << 24) + (r << 16) + (g << 8) + (b << 4); 

或者,如果您提取图像,也可以拍摄原始图像的alpha:

int rgb = img.getRGB(x, y);
int alpha = (rgb >>> 24);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb & 0xFF);

int newColour = (alpha << 24) + (r << 16) + (g << 8) + (b << 4);

答案 1 :(得分:1)

还有一个颜色组件:alpha通道。它存储在24-31位的数字中。如果设置为0,则图像是透明的。因此,您需要将24-31位的newColor设置为1以使其不透明。