Shawn Lauzon
Shawn Lauzon

Reputation: 6282

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.

Upvotes: 7

Views: 3284

Answers (2)

Howard
Howard

Reputation: 1

In native part of the bitmap.compress implement it wrote:

None of the JavaCompressFormats have a sensible way to compress an ALPHA_8 Bitmap. SkPngEncoder will compress one, but it uses a non-standard format that most decoders do not understand, so this is likely not useful.

So you can't compress an ALPHA_8 Bitmap.

Upvotes: 0

Shawn Lauzon
Shawn Lauzon

Reputation: 6282

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!

Upvotes: 8

Related Questions