java - 使用 RGBA 中的 alpha 设置图像的不透明度

标签 java image opacity rgb rgba

我试图制作一个简单的程序来加载图像,使其具有蓝色效果,并使其半透明。我通过在图像像素上运行并更改 RGB 的蓝色值和 alpha 值来实现。我成功地为图像制作了漂亮的蓝色效果。但我无法设法改变图像的不透明度。看来无论我如何改变像素的alpha值,都不会影响图像。

这是我的代码:

try {
    image1 = ImageIO.read(new File("image1.png"));
} catch(IOException e) {e.printStackTrace();}


for(int x=0;x<image1.getWidth();x++) {
    for(int y=0;y<image1.getHeight();y++) {
        int rgb = image1.getRGB(x, y);
        Color color = new Color(rgb);
        int r = color.getRed();
        int g = color.getGreen();
        int b = color.getBlue();
        int a = color.getAlpha();

        System.out.println(a);
        a= 100;
        if(b<155)
            b+=100;
        else
            b=255;

        color = new Color(r,g,b,a);

        image1.setRGB(x, y, color.getRGB());
    }
}

更新: 我也试过这个。还是不行:

for(int x=0;x<image1.getWidth();x++) {
    for(int y=0;y<image1.getHeight();y++) {
        int rgb = image1.getRGB(x, y);
        Color color = new Color(rgb,true);
        int r = color.getRed();
        int g = color.getGreen();
        int b = color.getBlue();
        int a = color.getAlpha();

        a= 100;
        if(b<155)
            b+=100;
        else
            b=255;


        rgb = rgb | b;
        rgb = rgb & 0x33ffffff;


        image1.setRGB(x, y, rgb);
    }
}

最佳答案

使用 AlphaComposite :

BufferedImage img = //some code here
BufferedImage imgClone = //some clone of img, but let its type be BufferedImage.TYPE_INT_ARGB
Graphics2D imgCloneG = imgClone.createGraphics();
imgCloneG.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN, 0.5f));
imgCloneG.drawImage(img, 0, 0, null);
//imgClone is now img at half alpha

imgClone 可以这样制作:

...
imgClone = new BufferedImage(img.getWidth(), img.getHeight(), 
                             BufferedImage.TYPE_INT_ARGB);
Graphics2D imgCloneG = imgClone.createGraphics();
imgCloneG.drawImage(img, 0, 0, null);
imgCloneG.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN, 0.5f));
...

关于java - 使用 RGBA 中的 alpha 设置图像的不透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16156343/

相关文章:

c# - 在将 Thread.Sleep 与 pictureBox 一起使用时,Winform 卡住

java - Jython - 尝试连接到数据库会导致 java.sql.SQLException : No suitable driver found

java - Android,在方法之间传递 LinearLayout、RelativeLayout 和 TextView

python - 无法正确打开带枕头的透明图像

css - 背景图片 : how to fill whole div if image is small and vice versa

css - 不使用两个 div 的 div 中心的背景图像不透明度

html - 透明背景,不透明元素

java |垃圾收集器如何忽略没有引用的数组内存

java - 需要提取java中多行中存在的特定字符串

java - 单击按钮时连续图像加载/处理和显示(在 Swing 中)