Change color of non-transparent parts of png in Java

前端 未结 3 1289
遥遥无期
遥遥无期 2021-01-31 11:17

I am trying to automatically change the color for a set of icons. Every icon has a white filled layer and the other part is transparent. Here is an example: (in this case it\'s

相关标签:
3条回答
  • 2021-01-31 11:25

    Why it doesn't work, I don't know, this will.

    This changes all the pixles to blue, maintaining their alpha values...

    enter image description here

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-31 11:35

    The problem is, that

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

    discards all the alpha values. Instead you have to use

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

    to keep alpha values available.

    0 讨论(0)
  • 2021-01-31 11:40

    If your bitmap is already set in an ImageView, just do :

    imageView.setColorFilter(Color.RED);
    

    to set all non transparent pixels to red.

    0 讨论(0)
提交回复
热议问题