Search code examples
androidcanvasbitmappng

Bitmap.compress returns false for drawn image


I have some code where the user draws something on the screen and I want to store it as a PNG in a byte[]. However, the compress() method returns false. Any idea why that is? Is there a better way to get the byte[]?

Bitmap bm = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ALPHA_8);
Canvas c = new Canvas(bm);
c.drawPath(mSignaturePath, mSignaturePaint);
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (bm.compress(Bitmap.CompressFormat.PNG, 100, out)) {
    byte[] result = out.toByteArray(); // Never gets called
}

Thanks in advance.


Solution

  • The problem was in how I was creating the image:

    Bitmap bm = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ALPHA_8);
    

    When I changed that to Bitmap.Config.RGB_565 it worked fine.

    Thanks to Mark Murphy (@commonsware) for the advice during his office hours!