Android Camera onPreview中byte[]快速轉換爲Bitmap
在以前對幀率要求不高時,一直使用BitmapFactory.decodeByteArray來進行處理,耗時非常可觀,在只開前攝的情況下處理圖像,耗時達到了260ms,下面是以前的處理方式:
YuvImage yuvimage = new YuvImage(
yuvData,
ImageFormat.NV21,
size.width,
size.height,
null);//data是onPreviewFrame參數提供
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg( new Rect(0, 0,yuvimage.getWidth(), yuvimage.getHeight()), 100, baos);// 80--JPG圖片的質量[0-100],100最高
byte[] rawImage =baos.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inPreferredConfig = Bitmap.Config.RGB_565; //默認8888
//options.inSampleSize = 8;
SoftReference<Bitmap> softRef = new SoftReference<Bitmap>(BitmapFactory.decodeByteArray(rawImage, 0,rawImage.length,options));//方便回收
Bitmap bitmap = (Bitmap) softRef.get();
在新方法下,僅僅3~4ms就可完成對圖像的處理,需要使用Renderscript內聯函數,可以更快的轉換爲YUV圖像:
使用到的變量:
private RenderScript rs;
private ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic;
private Type.Builder yuvType, rgbaType;
private Allocation in, out;
在onCreate方法中創建:
rs = RenderScript.create(this);
yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
在onPreviewFrame方法中調用以下方法:
if (yuvType == null)
{
yuvType = new Type.Builder(rs, Element.U8(rs)).setX(dataLength);
in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);
rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(prevSizeW).setY(prevSizeH);
out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);
}
in.copyFrom(data);
yuvToRgbIntrinsic.setInput(in);
yuvToRgbIntrinsic.forEach(out);
Bitmap bmpout = Bitmap.createBitmap(prevSizeW, prevSizeH, Bitmap.Config.ARGB_8888);
out.copyTo(bmpout);
個人聯繫方式:[email protected]