How to replace color with another color in BufferedImage

前端 未结 3 1272
甜味超标
甜味超标 2021-01-14 08:22

So I have an image file that has a volcano on it. Everything else is 0xFFFF00FF (opaque magenta). I want to replace every pixel that contains that color with 0 (transparent)

3条回答
  •  梦谈多话
    2021-01-14 08:39

    You can get the pixels[] array of the buffered image like so

    int[] pixels = ((DataBufferInt) newImg().getDataBuffer()).getData();
    

    and then set your colors like so

    for (int i = 0; i < width; i++) {
        for (int j = 0; j < height; j++) {
            color = pixels[y * width + x];
            if (color == target) {
                pixels[y * width + x] = preferred;
            }
            else {
                pixels[y * width + x] = color;
            }
        }
    }
    

    This is a slight speed up over using setRGB()

提交回复
热议问题