查找問題
最近在項目中遇到將攝像頭數(shù)據(jù)處理后轉(zhuǎn)Bitmap的內(nèi)存溢出問題睛廊,大概運行到七八個小時后形真,就出現(xiàn)了內(nèi)存溢出,后來看了一下錯誤提示發(fā)現(xiàn)
bitmap = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
這個地方會導(dǎo)致出現(xiàn)問題超全,故對此需要進行優(yōu)化咆霜。
優(yōu)化之前
首先看一下原先的處理方式
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;
}
優(yōu)化之后
優(yōu)化后的處理如下:
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;
/**
* Created by caydencui on 2018/12/7.
*/
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;
}
}
優(yōu)化對比
對幀率要求不高時,一直使用BitmapFactory.decodeByteArray來進行處理嘶朱,耗時非扯昱鳎可觀,耗時達到60-80ms疏遏,在新方法下脉课,僅僅3~4ms就可完成對圖像的處理,需要使用Renderscript內(nèi)聯(lián)函數(shù)财异,可以更快的轉(zhuǎn)換為YUV圖像倘零,從而提供了性能,增加了程序的穩(wěn)定性.