Is there a way to allocate a Bitmap in JNI and use it in Java to avoid OOM error

Viewed 98

I have a drawing-board App and there's an "export image" function. I hope the exported image size can be as large as users want. The exporting steps are:

  1. create a bitmap;
  2. applying some transformation matrices;
  3. create a canvas on that bitmap and draw something on it.
  4. compress the bitmap and save to file

When using Java Bitmap.createBitmap, if the created bitmap is so large and the required memory reaches Android VM heap size limit, an OutOfMemoryError encountered.

To avoid the OOM error I'm considering to create a bitmap with native-allocated pixel data in JNI, and used the bitmap as a reference in Java. But so far I have no idea about how to achieve this at all even after I searched a lot.

Or if I can't do this, is there another way to draw canvas to a probably very large bitmap without OOM errors?

Thanks for any help!

1 Answers

If the end result is a file, you don't need to use Bitmap at all. Use a C or C++ image library and do everything natively. It'll also be MUCH faster (in fact Android decodes bitmap in C already, it's too slow in Java and pointers make it easier).

How big is the bitmap anyway? Remember that a bmp requires 4*width*height bytes in memory. There's a limit to how big of one you can create even in C based memory.

Related