Search code examples
javaandroidbitmapopacityalpha

How to change a bitmap's opacity?


I have a bitmap:

Bitmap bitmap = BitmapFactory.decodeFile("some/arbitrary/path/image.jpg");

But I'm not going to display the image to the user. I want the alpha to be 100 (out of 255). If this is not possible, can I set the opacity of the Bitmap?


Solution

  • You could also try BitmapDrawable instead of Bitmap. If this is useful for you depends on the way you use the bitmap...

    Edit

    As a commenter asked how he can store the bitmap with alpha, here is some code:

    // lets create a new empty bitmap
    Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
    // create a canvas where we can draw on
    Canvas canvas = new Canvas(newBitmap);
    // create a paint instance with alpha
    Paint alphaPaint = new Paint();
    alphaPaint.setAlpha(42);
    // now lets draw using alphaPaint instance
    canvas.drawBitmap(originalBitmap, 0, 0, alphaPaint);
    
    // now lets store the bitmap to a file - the canvas has drawn on the newBitmap, so we can just store that one
    // please add stream handling with try/catch blocks
    FileOutputStream fos = new FileOutputStream(new File("/awesome/path/to/bitmap.png"));
    newBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);