android 根据视频流 YUV byte[] 数据转成图片

如下代码 复制可以使用: 

 

调用方式: saveMyBitmap(byteArrayRGBABitmap(bata,width,height))

/**
 * 截图鱼眼效果
 *
 * @param data yuv视频流数据
 * @param width 宽
 * @param height 高
 * @return 
 */
public Bitmap byteArrayRGBABitmap(byte[] data, int width, int height) {

    int[] ints = yuvI420toARGB(data, width, height);
    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bmp.setPixels(ints, 0, width, 0, 0, width, height);
    return bmp;
}

public static int[] yuvI420toARGB(byte[] yuv, int width, int height) {

    int iterations = width * height;

    int[] rgb = new int[iterations];
    for (int i = 0; i < iterations; i++) {
        int nearest = (i / width) / 2 * (width / 2) + (i % width) / 2;
        int y = yuv[i] & 0x000000ff;
        int u = yuv[iterations + nearest] & 0x000000ff;

        int v = yuv[iterations + iterations / 4 + nearest] & 0x000000ff;

        int b = (int) (y + 1.8556 * (u - 128));

        int g = (int) (y - (0.4681 * (v - 128) + 0.1872 * (u - 128)));

        int r = (int) (y + 1.5748 * (v - 128));

        if (b > 255) {
            b = 255;
        } else if (b < 0) {
            b = 0;
        }
        if (g > 255) {
            g = 255;
        } else if (g < 0) {
            g = 0;
        }
        if (r > 255) {
            r = 255;
        } else if (r < 0) {
            r = 0;
        }
        rgb[i] = (0xff000000) | (0x00ff0000 & r << 16) | (0x0000ff00 & g << 8) | (0x000000ff & b);
    }
    return rgb;

}

//保存文件到指定路径
private void saveMyBitmap(Bitmap bitmap) {

    File sd = Environment.getExternalStorageDirectory();

    File destDir = new File(sd.getPath() + "/DCIM/" + "Camera/");
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    String tmpfile = sd.getPath() + "/DCIM/" + "Camera/" + System.currentTimeMillis() + ".jpg";

    BufferedOutputStream bos = null;
    try {
        try {
            bos = new BufferedOutputStream(new FileOutputStream(tmpfile));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);
        bitmap.recycle();
    } catch (Exception e) {
        Log.e(TAG, "截屏失败");
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (bos != null)
            try {
                bos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
    // 最后通知图库更新
    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + tmpfile)));
 
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值