19

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

图标搜索

我尝试执行以下操作:

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 值。

4

4 回答 4

20

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

这会将所有像素更改为蓝色,保持它们的 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;
    }
}
于 2013-04-17T08:16:02.613 回答
15

问题是,那

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

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

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

保持 alpha 值可用。

于 2013-04-17T08:12:12.920 回答
0

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

imageView.setColorFilter(Color.RED);

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

于 2020-12-02T18:58:26.580 回答
0

由于我们将始终只替换 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]);    
}
于 2022-01-23T12:02:11.333 回答