RenderScriptを使用してyuvストリームをbitmapクラスにすばやく変換

2930 ワード

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レイヤのメモリが漏洩します.