天天看點

android bitmap nv21,Android——Nv21高效率轉Bitmap

查找問題

最近在項目中遇到将攝像頭資料處理後轉Bitmap的記憶體溢出問題,大概運作到七八個小時後,就出現了記憶體溢出,後來看了一下錯誤提示發現bitmap = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());

這個地方會導緻出現問題,故對此需要進行優化。

優化之前

首先看一下原先的處理方式private static Bitmap nv21ToBitmap(byte[] nv21, int width, int height) {

Bitmap bitmap = null; try {

YuvImage image = new YuvImage(nv21, ImageFormat.NV21, width, height, null);

ByteArrayOutputStream stream = new ByteArrayOutputStream();

image.compressToJpeg(new Rect(0, 0, width, height), 80, stream);

bitmap = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());

stream.close();

} catch (IOException e) {

e.printStackTrace();

} return bitmap;

}

優化之後

優化後的處理如下:package com.cdigi.facedep.util;import android.content.Context;import android.graphics.Bitmap;import android.renderscript.Allocation;import android.renderscript.Element;import android.renderscript.RenderScript;import android.renderscript.ScriptIntrinsicYuvToRGB;import android.renderscript.Type;public class NV21ToBitmap { private RenderScript rs; private ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic; private Type.Builder yuvType, rgbaType; private Allocation in, out; public NV21ToBitmap(Context context) {

rs = RenderScript.create(context);

yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));

} public Bitmap nv21ToBitmap(byte[] nv21, int width, int height){ if (yuvType == null){

yuvType = new Type.Builder(rs, Element.U8(rs)).setX(nv21.length);

in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);

rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height);

out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);

}

in.copyFrom(nv21);

yuvToRgbIntrinsic.setInput(in);

yuvToRgbIntrinsic.forEach(out);

Bitmap bmpout = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

out.copyTo(bmpout); return bmpout;

}

}

優化對比

對幀率要求不高時,一直使用BitmapFactory.decodeByteArray來進行處理,耗時非常可觀,耗時達到60-80ms,在新方法下,僅僅3~4ms就可完成對圖像的處理,需要使用Renderscript内聯函數,可以更快的轉換為YUV圖像,進而提供了性能,增加了程式的穩定性.

作者:一杯茶一本書

連結:https://www.jianshu.com/p/d61443506687