Android原生超快NV21格式視頻流YUV轉(zhuǎn)Bitmap外加圖片變換

import android.content.Context;
import android.graphics.Bitmap;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicYuvToRGB;
import android.renderscript.Type;

/**
 * 使用RenderScript將視頻YUV流轉(zhuǎn)換為BMP
 * 注:這個類適用于CameraPreview不變的情況
 */
public class FastYUVtoRGB {
    private RenderScript rs;
    private ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic;
    private Type.Builder yuvType, rgbaType;
    private Allocation in, out;

    public FastYUVtoRGB(Context context) {
        rs = RenderScript.create(context);
        yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
    }


    public Bitmap convertYUVtoRGB(byte[] yuvData, int width, int height) {
        if (yuvType == null) {
            yuvType = new Type.Builder(rs, Element.U8(rs)).setX(yuvData.length);
            in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);

            rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height);
            out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);
        }
        in.copyFrom(yuvData);
        yuvToRgbIntrinsic.setInput(in);
        yuvToRgbIntrinsic.forEach(out);
        Bitmap bmpout = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        out.copyTo(bmpout);
        return bmpout;
    }
}

當(dāng)有了bitmap之后甸饱,如果使用Bitmap.createBitmap()方法來進(jìn)行圖片變換狭姨,速度較慢耀态,推薦使用canvas來變換bitmap
首先需要構(gòu)建正確的變換矩陣(代碼來自于tensorflow官方git)
更新:加入水平翻轉(zhuǎn)與垂直翻轉(zhuǎn)參數(shù)

        /**
     * Returns a transformation matrix from one reference frame into another.
     * Handles cropping (if maintaining aspect ratio is desired) and rotation.
     *
     * @param srcWidth            Width of source frame.
     * @param srcHeight           Height of source frame.
     * @param dstWidth            Width of destination frame.
     * @param dstHeight           Height of destination frame.
     * @param applyRotation       Amount of rotation to apply from one frame to another.
     *                            Must be a multiple of 90.
     * @param flipHorizontal      should flip horizontally
     * @param flipVertical        should flip vertically
     * @param maintainAspectRatio If true, will ensure that scaling in x and y remains constant,
     *                            cropping the image if necessary.
     * @return The transformation fulfilling the desired requirements.
     */
    public static Matrix getTransformationMatrix(
            final int srcWidth,
            final int srcHeight,
            final int dstWidth,
            final int dstHeight,
            final int applyRotation, boolean flipHorizontal, boolean flipVertical,
            final boolean maintainAspectRatio) {
        final Matrix matrix = new Matrix();

        if (applyRotation != 0) {
            if (applyRotation % 90 != 0) {
                throw new IllegalArgumentException(String.format("Rotation of %d % 90 != 0", applyRotation));
            }

            // Translate so center of image is at origin.
            matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f);

            // Rotate around origin.
            matrix.postRotate(applyRotation);
        }

        // Account for the already applied rotation, if any, and then determine how
        // much scaling is needed for each axis.
        final boolean transpose = (Math.abs(applyRotation) + 90) % 180 == 0;

        final int inWidth = transpose ? srcHeight : srcWidth;
        final int inHeight = transpose ? srcWidth : srcHeight;

        int flipHorizontalFactor = flipHorizontal ? -1 : 1;
        int flipVerticalFactor = flipVertical ? -1 : 1;

        // Apply scaling if necessary.
        if (inWidth != dstWidth || inHeight != dstHeight) {
            final float scaleFactorX = flipHorizontalFactor * dstWidth / (float) inWidth;
            final float scaleFactorY = flipVerticalFactor * dstHeight / (float) inHeight;

            if (maintainAspectRatio) {
                // Scale by minimum factor so that dst is filled completely while
                // maintaining the aspect ratio. Some image may fall off the edge.
                final float scaleFactor = Math.max(Math.abs(scaleFactorX), Math.abs(scaleFactorY));
                matrix.postScale(scaleFactor, scaleFactor);
            } else {
                // Scale exactly to fill dst from src.
                matrix.postScale(scaleFactorX, scaleFactorY);
            }
        }

        if (applyRotation != 0) {
            // Translate back from origin centered reference to destination frame.
            float dx = dstWidth / 2.0f;
            float dy = dstHeight / 2.0f;
            matrix.postTranslate(dx, dy);
            // postScale中心點如果出錯瘩燥,圖像不會被變換
            matrix.postScale(flipHorizontalFactor, flipVerticalFactor, dx, dy);
        }

        return matrix;
    }

然后使用上面得到的矩陣來快速變換Bitmap

   /*
    example
    */
    final Canvas canvas = new Canvas(out);
    // 這里的空白bitmap尺寸需要與變換后的預(yù)期尺寸一致
    Bitmap src = Bitmap.createBitmap(height, width, Bitmap.Config.ARGB_8888);
    Matrix transformation = getTransformationMatrix(src.getWidth(), src.getHeight(), targetWidth, targetHeight, rotation,true,false, true);
    canvas.drawBitmap(src, transformation, null);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市正林,隨后出現(xiàn)的幾起案子泡一,更是在濱河造成了極大的恐慌,老刑警劉巖觅廓,帶你破解...
    沈念sama閱讀 221,273評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鼻忠,死亡現(xiàn)場離奇詭異,居然都是意外死亡哪亿,警方通過查閱死者的電腦和手機粥烁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蝇棉,“玉大人讨阻,你說我怎么就攤上這事〈垡螅” “怎么了钝吮?”我有些...
    開封第一講書人閱讀 167,709評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長板辽。 經(jīng)常有香客問我奇瘦,道長,這世上最難降的妖魔是什么劲弦? 我笑而不...
    開封第一講書人閱讀 59,520評論 1 296
  • 正文 為了忘掉前任耳标,我火速辦了婚禮,結(jié)果婚禮上邑跪,老公的妹妹穿的比我還像新娘次坡。我一直安慰自己,他們只是感情好画畅,可當(dāng)我...
    茶點故事閱讀 68,515評論 6 397
  • 文/花漫 我一把揭開白布砸琅。 她就那樣靜靜地躺著,像睡著了一般轴踱。 火紅的嫁衣襯著肌膚如雪症脂。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,158評論 1 308
  • 那天淫僻,我揣著相機與錄音诱篷,去河邊找鬼。 笑死雳灵,一個胖子當(dāng)著我的面吹牛兴蒸,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播细办,決...
    沈念sama閱讀 40,755評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼橙凳,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了笑撞?” 一聲冷哼從身側(cè)響起岛啸,我...
    開封第一講書人閱讀 39,660評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎茴肥,沒想到半個月后坚踩,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,203評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡瓤狐,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,287評論 3 340
  • 正文 我和宋清朗相戀三年瞬铸,在試婚紗的時候發(fā)現(xiàn)自己被綠了批幌。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,427評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡嗓节,死狀恐怖荧缘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情拦宣,我是刑警寧澤截粗,帶...
    沈念sama閱讀 36,122評論 5 349
  • 正文 年R本政府宣布,位于F島的核電站鸵隧,受9級特大地震影響绸罗,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜豆瘫,卻給世界環(huán)境...
    茶點故事閱讀 41,801評論 3 333
  • 文/蒙蒙 一珊蟀、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧外驱,春花似錦系洛、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至趟薄,卻和暖如春绽诚,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背杭煎。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工恩够, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人羡铲。 一個月前我還...
    沈念sama閱讀 48,808評論 3 376
  • 正文 我出身青樓蜂桶,卻偏偏與公主長得像,于是被迫代替她去往敵國和親也切。 傳聞我的和親對象是個殘疾皇子扑媚,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,440評論 2 359

推薦閱讀更多精彩內(nèi)容