Because the camera Preview Data in android can only be in the imageformat. nv21 format, decoding should go through a twists and turns.
Camera mcamera = camera. open (); camera. parameters P = mcamera. getparameters (); p. setpreviewformat (imageformat. nv21);/* This is a unique value and can be left unspecified. Some users may set a value below pixelformat, which is actually incorrect. For details, refer to the official documentation */
Mcamera. setparameters (P );
Mcamera. startpreview ();
The following is the core part of decoding:
@ Overridepublic void onpreviewframe (byte [] data, camera) {size = camera. getparameters (). getpreviewsize (); try {yuvimage image = new yuvimage (data, imageformat. nv21, size. width, size. height, null); If (image! = NULL) {bytearrayoutputstream stream = new bytearrayoutputstream (); image. compresstojpeg (New rect (0, 0, size. width, size. height), 80, stream); bitmap BMP = bitmapfactory. decodebytearray (stream. tobytearray (), 0, stream. size (); stream. close () ;}} catch (exception ex) {log. E ("sys", "error:" + ex. getmessage ());}}
CodeVery simple. Convert YUV data to bitmap. The system provides the yuvimage class.