KOG
KOG

Reputation: 53

Android: How to make a percentage of a bitmap black and white, retaining color in the rest?

I've got a bitmap displayed in an ImageView, and I want to be able to make a certain percentage of the image black and white, and have the other part retain it's color. For example, if 60% is the target percentage, the image would look like this: would look like this. Thanks.

Upvotes: 3

Views: 873

Answers (1)

Jon Goodwin
Jon Goodwin

Reputation: 9153

I've got a bitmap displayed in an ImageView, and I want to be able to make a certain percentage of the image black and white, and have the other part retain it's color. For example, if 60% is the target percentage.

It seems (from your image) you mean monochrome (i.e. greyscale), not black and white.

Something like this should do it (tested o.k.):

void doIt(ImageView image)
{
    //get bitmap from your ImageView (image)
    Bitmap originalBitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();

    int height = originalBitmap.getHeight();
    int fortyPercentHeight = (int) Math.floor(height * 40.0 / 100.0);

    //create a bitmap of the top 40% of image height that we will make black and white
    Bitmap croppedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth() , fortyPercentHeight );
    //make it monochrome
    Bitmap blackAndWhiteBitmap = monoChrome(croppedBitmap);
    //copy the monochrome bmp (blackAndWhiteBitmap) to the original bmp (originalBitmap)
    originalBitmap = overlay(originalBitmap, blackAndWhiteBitmap);
    //set imageview to new bitmap
    image.setImageBitmap(originalBitmap );
}

Bitmap monoChrome(Bitmap bitmap)
{
    Bitmap bmpMonochrome = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bmpMonochrome);
    ColorMatrix ma = new ColorMatrix();
    ma.setSaturation(0);
    Paint paint = new Paint();
    paint.setColorFilter(new ColorMatrixColorFilter(ma));
    canvas.drawBitmap(bitmap, 0, 0, paint);
    return bmpMonochrome;
}

Bitmap overlay(Bitmap bmp1, Bitmap bmp2) 
{
    Bitmap bmp3 = bmp1.copy(Bitmap.Config.ARGB_8888,true);//mutable copy
    Canvas canvas = new Canvas(bmp3 );
    canvas.drawBitmap(bmp2, new Matrix(), null);
    return bmp3 ;
}

Upvotes: 2

Related Questions