使用RenderScript 将yuv流快速转换bitmap类

public static Bitmap getBitmapFromFrameData(RenderScript rs, ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic, byte[] data, int width, int height) {
        Type.Builder yuvType = null, rgbaType;
        Allocation in = null, out = null;
        try {

            final int w = width;  //宽度
            final int h = height;
            Bitmap bitmap;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                if (yuvType == null) {
                    yuvType = new Type.Builder(rs, Element.U8(rs)).setX(data.length);
                    in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);
                    rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(w).setY(h);
                    out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);
                }

                in.copyFrom(data);
                yuvToRgbIntrinsic.setInput(in);
                yuvToRgbIntrinsic.forEach(out);
                bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
                out.copyTo(bitmap);

            } else {
                ByteArrayOutputStream baos;
                byte[] rawImage;
                //处理data
                BitmapFactory.Options newOpts = new BitmapFactory.Options();
                newOpts.inJustDecodeBounds = true;
                YuvImage yuvimage = new YuvImage(
                        data,
                        ImageFormat.NV21,
                        w,
                        h,
                        null);
                baos = new ByteArrayOutputStream();
                yuvimage.compressToJpeg(new Rect(0, 0, w, h), 100, baos);// 80--JPG图片的质量[0-100],100最高
                rawImage = baos.toByteArray();
                //将rawImage转换成bitmap
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length, options);
            }
            in = null;
            out = null;
            return bitmap;
        } catch (Throwable e) {
            in = null;
            out = null;
            return null;
        }
    }

利用RenderScript将byte数据快速转换成bitmap的类,保存一下,以备后用

//调用方式
//        try {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//                rs = RenderScript.create(this);
//                yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
//            }
//        } catch (Throwable e) {
//
//        }

 

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

#最后,ondetory的时候,一定要记得释放,否则会造成java层会内存泄漏。

你可能感兴趣的:(android开发)