使用Camera2采集相机预览数据,一般推荐格式为YUV,而目前主流的图像处理算法却只针对RGB的,所以一般需要先将YUV图片格式转为RGB,在Android中为Bitmap。
这里有两个方式,一种是先转为jpg,再通过jpg转为Bitmap:
YuvImage yuvImage = new YuvImage(nv21, ImageFormat.NV21, stride, height, null);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0, 0, stride, height), 100, byteArrayOutputStream);
Bitmap previewBitmap = null;
try {
byte[] jpgBytes = byteArrayOutputStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = ImageUtil.getSampleSize(mPreferSize, stride, height);
// 原始预览数据生成的bitmap
final Bitmap originalBitmap = BitmapFactory.decodeByteArray(jpgBytes, 0, jpgBytes.length, options);
Matrix matrix = new Matrix();
// 预览相对于原数据可能有旋转
matrix.postRotate(90);
// 和预览画面相同的bitmap
previewBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(), originalBitmap.getHeight(), matrix, false);
originalBitmap.recycle();
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
这里有个缩小和旋转的过程,inSampleSize 为缩小倍数。
第二种方式是使用ScriptIntrinsicYuvToRGB和Allocation直接将YUV转为RGB:
package *****;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.renderscript.Allocati