Converting Bitmap in memory to Bitmap with Bitmap.Config.RGB_565

Euthyphro picture Euthyphro · Feb 25, 2013 · Viewed 20.8k times · Source

I have a loaded Bitmap which I would like to convert to set the config to Bitmap.Config.RGB_565. Is there a simple way of converting a Bitmap to this configuration after the Bitmap is already loaded into memory? For example, below I have a bitmap being decoded from the application resources, however, how would I convert an already loaded Bitmap to RGB_565? I'm sure it's something simple, however, I'm fairly new to working with Bitmaps and after a few hours of looking online, unfortunately I couldn't find what I needed specifically.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig=Bitmap.Config.RGB_565
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.myphoto ,options);

Answer

Emanuel Moecklin picture Emanuel Moecklin · Feb 25, 2013

I haven't tested this but it should work:

private Bitmap convert(Bitmap bitmap, Bitmap.Config config) {
    Bitmap convertedBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), config);
    Canvas canvas = new Canvas(convertedBitmap);
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    canvas.drawBitmap(bitmap, 0, 0, paint);
    return convertedBitmap;
}

call the methods like this:

Bitmap convertedBitmap = convert(bitmap, Bitmap.Config.RGB_565);

You can do all kinds of additional transformations like rotating, stretching etc. if you use the drawBitmap with a Matrix.