How to replace color with another color in BufferedImage

前端 未结 3 1244
甜味超标
甜味超标 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:45

    While I haven't had a chance to test this thoroughly yet, using a LookupOp may well benefit from acceleration:

    public class ColorMapper
    extends LookupTable {
    
        private final int[] from;
        private final int[] to;
    
        public ColorMapper(Color from,
                           Color to) {
            super(0, 4);
    
            this.from = new int[] {
                from.getRed(),
                from.getGreen(),
                from.getBlue(),
                from.getAlpha(),
            };
            this.to = new int[] {
                to.getRed(),
                to.getGreen(),
                to.getBlue(),
                to.getAlpha(),
            };
        }
    
        @Override
        public int[] lookupPixel(int[] src,
                                 int[] dest) {
            if (dest == null) {
                dest = new int[src.length];
            }
    
            int[] newColor = (Arrays.equals(src, from) ? to : src);
            System.arraycopy(newColor, 0, dest, 0, newColor.length);
    
            return dest;
        }
    }
    

    Using it is as easy as creating a LookupOp:

    Color from = Color.decode("#ff00ff");
    Color to = new Color(0, true);
    BufferedImageOp lookup = new LookupOp(new ColorMapper(from, to), null);
    BufferedImage convertedImage = lookup.filter(image, null);
    

提交回复
热议问题