.JPG/.PNG转NV21格式

一般来说,如果能够获得Bitmap对象的引用,就需要及时的调用Bitmap的recycle()方法来释放Bitmap占用的内存空间,而不要等Android系统来进行释放。
参考博文 如何理解与有效避免安卓加载Bitmap造成的OOM异常
  下面是释放Bitmap的示例代码片段。

  // 先判断是否已经回收
  if(bitmap != null && !bitmap.isRecycled()){
  // 回收并且置为null
  bitmap.recycle();
  bitmap = null;
  }
  System.gc()

.JPG/.PNG转NV21格式的函数
参考问答 JPG转换为NV21格式

注意要引入 ImageConverter
implementation ‘com.guo.android_extend:android-extend:1.0.5’

//imagePath是绝对路径
    private byte[] imgToNV21(String imagePath){
        Bitmap bmp=null;
        try{
            bmp= BitmapFactory.decodeFile(imagePath);
        }catch (OutOfMemoryError e){
            e.printStackTrace();//bitmap容易出现内存泄漏,加个异常捕获
        }
        if(bmp == null){
            Log.d("MainActivity","Bitmap error");
        }

        byte[] mImageNV21 = new byte[bmp.getWidth() * bmp.getHeight() * 3 / 2];
        ImageConverter convert = new ImageConverter();
        try{
            convert.initial(bmp.getWidth(), bmp.getHeight(), ImageConverter.CP_PAF_NV21);
            if (convert.convert(bmp, mImageNV21)) {
                Log.d("MainActivity", "convert ok!");
            }else {
                Log.d("MainActivity", "convert error!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
        //回收内存
            if(bmp !=null && !bmp.isRecycled()){
                bmp.recycle();
                bmp = null;
            }
            convert.destroy();
            System.gc();
        }
        return mImageNV21;
    }

你可能感兴趣的:(.JPG/.PNG转NV21格式)