繁体   English   中英

"在Java中更改png不透明部分的颜色"

[英]Change color of non-transparent parts of png in Java

我正在尝试自动更改一组图标的颜色。 每个图标都有一个白色填充层,另一部分是透明的。 这是一个例子:(在这种情况下它是绿色的,只是为了让它可见)

图标搜索

我尝试执行以下操作:

private static BufferedImage colorImage(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();

        for (int xx = 0; xx < width; xx++) {
            for (int yy = 0; yy < height; yy++) {
                Color originalColor = new Color(image.getRGB(xx, yy));
                System.out.println(xx + "|" + yy + " color: " + originalColor.toString() + "alpha: "
                        + originalColor.getAlpha());
                if (originalColor.equals(Color.WHITE) && originalColor.getAlpha() == 255) {
                    image.setRGB(xx, yy, Color.BLUE.getRGB());
                }
            }
        }
        return image;
    }

我遇到的问题是我得到的每个像素都具有相同的值:

32|18 color: java.awt.Color[r=255,g=255,b=255]alpha: 255

所以我的结果只是一个彩色方块。 如何实现仅更改非透明部分的颜色? 为什么所有像素都具有相同的 alpha 值? 我想这是我的主要问题:没有正确读取 alpha 值。

为什么它不起作用,我不知道,这会。

这会将所有像素更改为蓝色,并保持其 alpha 值...

在此处输入图片说明

import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class TestColorReplace {

    public static void main(String[] args) {
        try {
            BufferedImage img = colorImage(ImageIO.read(new File("NWvnS.png")));
            ImageIO.write(img, "png", new File("Test.png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private static BufferedImage colorImage(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        WritableRaster raster = image.getRaster();

        for (int xx = 0; xx < width; xx++) {
            for (int yy = 0; yy < height; yy++) {
                int[] pixels = raster.getPixel(xx, yy, (int[]) null);
                pixels[0] = 0;
                pixels[1] = 0;
                pixels[2] = 255;
                raster.setPixel(xx, yy, pixels);
            }
        }
        return image;
    }
}

问题是,那

Color originalColor = new Color(image.getRGB(xx, yy));

丢弃所有的 alpha 值。 相反,你必须使用

 Color originalColor = new Color(image.getRGB(xx, yy), true);

保持 alpha 值可用。

如果您的位图已经在 ImageView 中设置,只需执行以下操作:

imageView.setColorFilter(Color.RED);

将所有非透明像素设置为红色。

由于我们将始终只替换 RGB 像素的前三个波段,因此在不分配不必要的新数组的情况下实现相同效果的更有效方法是:

private static void colorImageAndPreserveAlpha(BufferedImage img, Color c) {
    WritableRaster raster = img.getRaster();
    int[] pixel = new int[] {c.getRed(),c.getGreen(),c.getBlue()};
    for (int x = 0; x < raster.getWidth(); x++) 
        for (int y = 0; y < raster.getHeight(); y++)
            for (int b = 0; b < pixel.length; b++)
                raster.setSample(x,y,b,pixel[b]);    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM