说明:项目中使用usb网络摄像头,在横屏版本使用后台看视频正常,但是需要适配竖屏版本的,竖屏视频传到后台是横着的,需要旋转90度。由于设备是嵌入式,编译耗时,单独截取一帧数据,用android方式来做,效率很高。
具体实现步骤:将nv12转成nv21,nv21再旋转90度,但是有些算法nv12转成nv21不支持
核心代码如下:
//调用,byteBuffer为nv12数据
byte[] raotaionData = port_nv12ToNv21(byteBuffer.array(), with, heiht);//没问题的旋转
byte[] des= rotateYUV420Degree90(raotaionData,with, heiht,90);
private byte[] port_nv12ToNv21(byte[] data, int width, int height) {
byte[] ret = new byte[width * height * 3 / 2];
int total = width * height;
ByteBuffer bufferY = ByteBuffer.wrap(ret, 0, total); // I420的Y分量
ByteBuffer bufferUV = ByteBuffer.wrap(ret, total, ret.length - total); // I420的U分量
// NV12 YYYYYYYY UVUV
bufferY.put(data, 0, total);
for (int i = total; i < data.length; i += 2) {
bufferUV.put(data[i + 1]);
bufferUV.put(data[i]);
}
return ret;
}
/**
* nv21旋转
*
* @param input
* @param width
* @param height
* @param rotation
* @return
*/
public byte[] rotateYUV420Degree90(byte[] input, int width, int height,
int rotation) {
int frameSize = width * height;
int qFrameSize = frameSize / 4;
byte[] output = new byte[frameSize + 2 * qFrameSize];
boolean swap = (rotation == 90 || rotation == 270);
boolean yflip = (rotation == 90 || rotation == 180);
boolean xflip = (rotation == 270 || rotation == 180);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int xo = x, yo = y;
int w = width, h = height;
int xi = xo, yi = yo;
if (swap) {
xi = w * yo / h;
yi = h * xo / w;
}
if (yflip) {
yi = h - yi - 1;
}
if (xflip) {
xi = w - xi - 1;
}
output[w * yo + xo] = input[w * yi + xi];
int fs = w * h;
int qs = (fs >> 2);
xi = (xi >> 1);
yi = (yi >> 1);
xo = (xo >> 1);
yo = (yo >> 1);
w = (w >> 1);
h = (h >> 1);
// adjust for interleave here
int ui = fs + (w * yi + xi) * 2;
int uo = fs + (w * yo + xo) * 2;
// and here
int vi = ui + 1;
int vo = uo + 1;
output[uo] = input[ui];
output[vo] = input[vi];
}
}
return output;
}
已经测试,代码可用