How to reduce or darken a bitmap

How to take an existing bitmap, say

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.somebitmap); 

and write a method that returns a darkened version of a bitmap?

 private Bitmap darkenBitMap(Bitmap bm) { } 

I am trying to use Paint and Canvas without any results.

+6
source share
4 answers

I finally get it. Hope this helps someone else.

 private Bitmap darkenBitMap(Bitmap bm) { Canvas canvas = new Canvas(bm); Paint p = new Paint(Color.RED); //ColorFilter filter = new LightingColorFilter(0xFFFFFFFF , 0x00222222); // lighten ColorFilter filter = new LightingColorFilter(0xFF7F7F7F, 0x00000000); // darken p.setColorFilter(filter); canvas.drawBitmap(bm, new Matrix(), p); return bm; } 
+19
source

Here is an example that iterates over each pixel.

 /** * @param bitmap a mutable bitmap instance. */ private void darkenBitmap(Bitmap bitmap) { int height = bitmap.getHeight(); int width = bitmap.getWidth(); int pixel; // Iterate over each row (y-axis) for (int y = 0; y < height; y++) { // and each column (x-axis) on that row for (int x = 0; x < width; x++) { pixel = bitmap.getPixel(x, y); // TODO: Modify your pixel here. For samples, http://stackoverflow.com/questions/4928772/android-color-darker bitmap.setPixel(x, y, pixel); } } } 

The method requires a modified bitmap, so you probably need to load the bitmap using the BitmapFactory options. eg.

 BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable = true; Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.somebitmap, options); 

You can also create a new mutable bitmap inside this method, call setPixel (...) on it and return it. But I highly recommend avoiding such memory allocation if possible.

0
source

To make viewing darker.

canvas.drawARGB(200, 0, 0, 0);

In short and simple :)

0
source
 private Bitmap darkenBitMap(Bitmap bm) { Canvas canvas = new Canvas(bm); canvas.drawARGB(1,0,0,0); canvas.drawBitmap(bm, new Matrix(), new Paint()); return bm; } 
0
source

All Articles