Android Camera onPreview中byte[]快速转换为Bitmap<耗时仅需3~4ms>

    xiaoxiao2021-12-14  19

    Android Camera onPreview中byte[]快速转换为Bitmap

    在以前对帧率要求不高时,一直使用BitmapFactory.decodeByteArray来进行处理,耗时非常可观,在只开前摄的情况下处理图像,耗时达到了260ms,下面是以前的处理方式:

    YuvImage yuvimage = new YuvImage( yuvData, ImageFormat.NV21, size.width, size.height, null);//data是onPreviewFrame参数提供 ByteArrayOutputStream baos = new ByteArrayOutputStream(); yuvimage.compressToJpeg( new Rect(0, 0,yuvimage.getWidth(), yuvimage.getHeight()), 100, baos);// 80--JPG图片的质量[0-100],100最高 byte[] rawImage =baos.toByteArray(); BitmapFactory.Options options = new BitmapFactory.Options(); //options.inPreferredConfig = Bitmap.Config.RGB_565; //默认8888 //options.inSampleSize = 8; SoftReference<Bitmap> softRef = new SoftReference<Bitmap>(BitmapFactory.decodeByteArray(rawImage, 0,rawImage.length,options));//方便回收 Bitmap bitmap = (Bitmap) softRef.get();

    在新方法下,仅仅3~4ms就可完成对图像的处理,需要使用Renderscript内联函数,可以更快的转换为YUV图像:

    使用到的变量:

    private RenderScript rs; private ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic; private Type.Builder yuvType, rgbaType; private Allocation in, out;

    在onCreate方法中创建:

    rs = RenderScript.create(this); yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));onPreviewFrame方法中调用以下方法:

    if (yuvType == null) { yuvType = new Type.Builder(rs, Element.U8(rs)).setX(dataLength); in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT); rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(prevSizeW).setY(prevSizeH); out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT); } in.copyFrom(data); yuvToRgbIntrinsic.setInput(in); yuvToRgbIntrinsic.forEach(out); Bitmap bmpout = Bitmap.createBitmap(prevSizeW, prevSizeH, Bitmap.Config.ARGB_8888); out.copyTo(bmpout);

    个人联系方式:15010399702@163.com

    转载请注明原文地址: https://ju.6miu.com/read-962288.html

    最新回复(0)