Android直播页或相机预览页卡顿的解决办法

1,出现卡顿的一种可能原因是:摄像头返回的图片帧源数据每一帧都被做了大量的逻辑处理,如缩放,裁剪,旋转,镜像等,导致不流畅或卡顿的现象发生。如果是这个原因,那么优化图片处理的过程就变得非常必要,这时候需要用到Google官方的一个图片处理库libyuv,下载地址:https://download.csdn.net/download/look_up_at/10979014

2,libyuv库的使用

首先将该库下载到本地,然后以library的形式依赖到项目中,然后就可以在需要处理图片的地方使用了。

下面这段代码是我的项目中对图片源数据处理后返回的图片帧bitmap,经过该库处理后的FPS最少在30帧以上。

    public static Bitmap yuvData2Bitmap(byte[] yuvData, int width, int height) {
        final long searchStartTime = System.currentTimeMillis();

        //YUV数据的压缩,旋转,镜像操作
        int newWidth = 720;
        int newHeight = 1280;
        final byte[] newYuvData = new byte[newHeight * newWidth * 3 / 2];
        YuvUtil.compressYUV(yuvData, width, height, newYuvData, newHeight, newWidth, 0, Constant.DEVICE_TYPE == 1 ? 90 : 270, true);
        //YUV数据的裁剪
//        byte[] cropData = new byte[cropWidth * cropHeight * 3 / 2];
//        YuvUtil.cropYUV(dstData, width, height, cropData, cropWidth, cropHeight, 0, 0);
        //YUV数据转化
        byte[] nv21Data = new byte[newHeight * newWidth * 3 / 2];
        YuvUtil.yuvI420ToNV21(newYuvData, nv21Data, newWidth, newHeight);
        long yuvProcessingEndTime = System.currentTimeMillis();
        Log.i(TAG, "onNext: YUV数据旋转,压缩,镜像处理耗时" + (yuvProcessingEndTime - searchStartTime) + "毫秒");

        YuvImage yuvImage = new YuvImage(nv21Data, ImageFormat.NV21, newWidth, newHeight, null);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        yuvImage.compressToJpeg(new Rect(0, 0, yuvImage.getWidth(), yuvImage.getHeight()), 100, outputStream);

        byte[] jpegData = outputStream.toByteArray();
        long photoDataProcessingEndTime = System.currentTimeMillis();
        Log.i(TAG, "onNext: yuv转bitmap耗时" + (photoDataProcessingEndTime - yuvProcessingEndTime) + "毫秒");
        Log.i(TAG, "onNext: 图片预处理总耗时" + (photoDataProcessingEndTime - searchStartTime) + "毫秒");
        return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length);
    }

猜你喜欢

转载自blog.csdn.net/look_up_at/article/details/87975173