Search code examples
androidbitmappixel

Change pixels in bitmap


I want to change pixels of my bitmap dynamically, but it is not mutable, so it return an IllegalStateException.

Here my code :

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
int[] pixels = new int[bm.getWidth()*bm.getHeight()]; 
 bm.getPixels(pixels, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight());

// ...work on pixels...

bm.setPixels(pixels, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight());

Solution

  • For example, to turn the first four rows of the bitmap blue:

    import android.graphics.Color;
    
    int[] pixels = new int[myBitmap.getHeight()*myBitmap.getWidth()];
    myBitmap.getPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
    for (int i=0; i<myBitmap.getWidth()*4; i++)
        pixels[i] = Color.BLUE;
    myBitmap.setPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
    

    You can also set a pixel's color in a Bitmap object one at a time without having to set up a pixel buffer with the setPixel() method:

    myBitmap.setPixel(x, y, Color.rgb(45, 127, 0));
    

    Use below method to get Mutable Bitmap from Resources

        public static Bitmap getMutableBitmap(Resources resources,int resId) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inMutable = true;
        return BitmapFactory.decodeResource(resources, resId, options);
    }
    

    or use

    Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
    

    to get mutable Bitmap from immutable bitmap.