Android——Nv21高效率转Bitmap

栏目: IOS · Android · 发布时间: 7年前

内容简介:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cuiran/article/details/85329158

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cuiran/article/details/85329158

查找问题

最近在项目中遇到将摄像头数据处理后转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;
/**
 * 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;
 }
}

优化对比

对帧率要求不高时,一直使用BitmapFactory.decodeByteArray来进行处理,耗时非常可观,耗时达到60-80ms,在新方法下,仅仅3~4ms就可完成对图像的处理,需要使用Renderscript内联函数,可以更快的转换为YUV图像,从而提供了性能,增加了程序的稳定性.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

数据库索引设计与优化

数据库索引设计与优化

【美】Tapio Lahdenmaki、【美】Michael Leach / 曹怡倩、赵建伟 / 电子工业出版社 / 2015-6 / 79.00元

《数据库索引设计与优化》提供了一种简单、高效、通用的关系型数据库索引设计方法。作者通过系统的讲解及大量的案例清晰地阐释了关系型数据库的访问路径选择原理,以及表和索引的扫描方式,详尽地讲解了如何快速地估算SQL 运行的CPU 时间及执行时间,帮助读者从原理上理解SQL、表及索引结构、访问方式等对关系型数据库造成的影响,并能够运用量化的方法进行判断和优化,指导关系型数据库的索引设计。 《数据库索......一起来看看 《数据库索引设计与优化》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具