I believe that some android& image algorithm developers, like me, have encountered this situation: to do some dense computation of the bitmap object (such as pixel-by-bit filtering), but in the Java layer write loop code to pixel-wise operation is obviously unrealistic, because the Java code is running too slow, A small 240*320 image has 76,800 pixels, and if the RGB three-channel (or ARGB four-channel) is considered, multiply the number by 3/4. Therefore, the dense computation of the image generally uses the JNI interface, which is implemented by C + +. So the question is, how do you get the pixel data from the bitmap to the C + + layer from the Java layer?
Procedure 1: The previous procedure
I did this because the bitmap class does not support the direct acquisition of pixel data, so I use the Copypixelstobuffer function to copy the pixel data into a buffer, and then upload the buffer data to the C + + layer for processing, after processing is done, Then use the Copypixelsfrombuffer function to assign the processed pixel data to the bitmap object. The disadvantage of this approach is that you need to request an additional chunk of memory, which is almost as large as the current image, as buffer and add two additional copy operations. We used C + + to process pixels to save time, and now the extra demand has increased the complexity of time and space, which is not an affordable way.
Procedure 2: The present practice
In fact, the Android NDK can be processed to some extent from the Java Layer Bitmap object, you can transfer the bitmap object to the C + + layer, directly get the pixel data pointer, do further processing. The steps are as follows:
A. Writing JNI interface functions
// Java interface Functions Private Static native int Processbitmap (Bitmap Bitmap); // corresponding C + + functions *env, Jclass,jobject bmpobj);
B. Adding a #include<android/bitmap.h> statement
#include <android/bitmap.h>
C. Get the pixel data pointer for action
Androidbitmapinfo bmpinfo={0}; if (Androidbitmap_getinfo (env,bmpobj,&bmpinfo) <0) {return -1} int* datafrombmp=NULL; if (Androidbitmap_lockpixels (Env,bmpobj, (void*) &datafrombmp)) {return -1;}
androidbitmap_lockpixels is used to get the data pointer, the parameter type of the data pointer is (void**), because Android bitmap generally store is ARGB format, if need is pixel, can use int* pointer, If you need a channel, you can use unsigned char*.
D. Operation complete, release the pointer
Androidbitmap_unlockpixels (Env,bmpobj);
This allows you to manipulate the pixel data in the bitmap directly without any duplication.
3. Other issues
If you need to create a bitmap object in the C + + layer, and then return to the Java layer, this requirement I have not found a specific implementation method, if anyone knows, please do not hesitate to advise
Using C + + to process bitmap objects in Android