Replace black color in bitmap with red

后端 未结 3 1205
南笙
南笙 2020-12-05 10:36

How can I replace the black color in a bitmap with red (or any other color) programmatically in Android (ignoring transparency)? I can replace the white color in the bitmap

3条回答
  •  星月不相逢
    2020-12-05 11:17

    This works for me

        public Bitmap replaceColor(Bitmap src,int fromColor, int targetColor) {
        if(src == null) {
            return null;
        }
        // Source image size
        int width = src.getWidth();
        int height = src.getHeight();
        int[] pixels = new int[width * height];
        //get pixels
        src.getPixels(pixels, 0, width, 0, 0, width, height);
    
        for(int x = 0; x < pixels.length; ++x) {
            pixels[x] = (pixels[x] == fromColor) ? targetColor : pixels[x];
        }
        // create result bitmap output
        Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());
        //set pixels
        result.setPixels(pixels, 0, width, 0, 0, width, height);
    
        return result;
    }
    

    Now set your bit map

    replaceColor(bitmapImg,Color.BLACK,Color.GRAY  )
    

    For better view please check this Link

提交回复
热议问题