// 获取bitmap
Bitmap b = Bitmap.createBitmap(activity.getWindow().getDecorView().getWidth(),
activity.getWindow().getDecorView().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
activity.getWindow().getDecorView().draw(canvas);
int[] argb = new int[inputWidth * inputHeight];
// Bitmap 获取 argb
b.getPixels(argb, 0, inputWidth, 0, 0, inputWidth, inputHeight);
byte[] yuv = new byte[inputWidth * inputHeight * 3 / 2];
// argb 8888 转 i420
conver_argb_to_i420(yuv, argb, inputWidth, inputHeight);
// argb 8888 转 i420
public static void conver_argb_to_i420(byte[] i420, int[] argb, int width, int height) {
final int frameSize = width * height;
int yIndex = 0; // Y start index
int uIndex = frameSize; // U statt index
int vIndex = frameSize*5/4; // V start index: w*h*5/4
int a, R, G, B, Y, U, V;
int index = 0;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
a = (argb[index] & 0xff000000) >> 24; // is not used obviously
R = (argb[index] & 0xff0000) >> 16;
G = (argb[index] & 0xff00) >> 8;
B = (argb[index] & 0xff) >> 0;
// well known RGB to YUV algorithm
Y = ( ( 66 * R + 129 * G + 25 * B + 128) >> 8) + 16;
U = ( ( -38 * R - 74 * G + 112 * B + 128) >> 8) + 128;
V = ( ( 112 * R - 94 * G - 18 * B + 128) >> 8) + 128;
// I420(YUV420p) -> YYYYYYYY UU VV
i420[yIndex++] = (byte) ((Y < 0) ? 0 : ((Y > 255) ? 255 : Y));
if (j % 2 == 0 && i % 2 == 0) {
i420[uIndex++] = (byte)((U<0) ? 0 : ((U > 255) ? 255 : U));
i420[vIndex++] = (byte)((V<0) ? 0 : ((V > 255) ? 255 : V));
}
index ++;
}
}
}