Replace black color in bitmap with red

后端 未结 3 886
南笙
南笙 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:06

    @nids : Have you tried replacing your Color to Color.TRANSPARENT ? That should work...

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-05 11:27

    Get all the pixels in the bitmap using this:

    int [] allpixels = new int [myBitmap.getHeight() * myBitmap.getWidth()];
    
    myBitmap.getPixels(allpixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
    
    for(int i = 0; i < allpixels.length; i++)
    {
        if(allpixels[i] == Color.BLACK)
        {
            allpixels[i] = Color.RED;
        }
    }
    
    myBitmap.setPixels(allpixels,0,myBitmap.getWidth(),0, 0, myBitmap.getWidth(),myBitmap.getHeight());
    
    0 讨论(0)
提交回复
热议问题