如何阻止java将BuffereImage设置为完全透明?

如何阻止java将BuffereImage设置为完全透明?,java,transparency,bufferedimage,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) {

我试图用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);

                }
          }

    }

}
导入java.awt.image.buffereImage;
公共类负片{
公共负片(BuffereImage img){
对于(int x=0;x>16)和0xFF;
int g=(rgb>>8)&0xFF;
intb=(rgb&0xFF);
r=255-r;
g=255-g;
b=255-b;

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

问题 他们所谓的RGB颜色实际上是ARGB,每个8位。 Alpha以最高8位表示,0表示透明,255表示完全不透明

这就是
TYPE\u INT\u ARGB
在javadoc中对于
buffereImage.setRGB()
的含义:

假定该像素位于默认RGB颜色模型、类型_INT_ARGB和默认sRGB颜色空间中

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

int newColour = (0xff << 24) + (r << 16) + (g << 8) + (b << 4); 
intnewcolor=(0xff>16)&0xff;
int g=(rgb>>8)&0xFF;
intb=(rgb&0xFF);

int newcolor=(alpha)您创建了一个只有构造函数的类,并将该构造函数称为Oo…只需将negative作为一个方法,而不需要类。与您的问题无关,但是,修复它谢谢!这非常有用!
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);