Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2012 www.amsoft.cn
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.graphics.Bitmap;

import android.graphics.Rect;

public class Main {
    /**
     * 
     * TODO
     * ImageFormat.NV21 || format == ImageFormat.YUY2.
     * @param data
     * @param width
     * @param height
     * @param rect
     * @return
     */
    public static Bitmap cropYuv2Bitmap(byte[] data, int width, int height, Rect rect) {
        int w = rect.width();
        int h = rect.height();
        int frameSize = width * height;
        int[] pixels = new int[w * h];
        byte[] yuv = data;
        int yOffset = rect.top * width + rect.left;
        int uvOffset = (rect.top / 2) * width + (rect.left / 2) * 2 + frameSize;
        int y, u, v, k;

        for (int i = 0; i < h; ++i) {
            int outputOffset = i * w;
            for (int j = 0; j < w; ++j) {
                y = (0xff & yuv[yOffset + j]) - 16;

                k = ((j >> 1) << 1);
                v = (0xff & yuv[uvOffset + k]) - 128;
                u = (0xff & yuv[uvOffset + k + 1]) - 128;

                int y1192 = 1192 * y;
                int r = (y1192 + 1634 * v);
                int g = (y1192 - 833 * v - 400 * u);
                int b = (y1192 + 2066 * u);

                if (r < 0)
                    r = 0;
                else if (r > 262143)
                    r = 262143;
                if (g < 0)
                    g = 0;
                else if (g > 262143)
                    g = 262143;
                if (b < 0)
                    b = 0;
                else if (b > 262143)
                    b = 262143;

                pixels[outputOffset + j] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00)
                        | ((b >> 10) & 0xff);
            }
            yOffset += width;
            if (((rect.top + i) & 1) == 1) {
                uvOffset += width;
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, w, 0, 0, w, h);
        return bitmap;
    }
}