android I420转NV21 , NV21转I420

    /**
     * I420转nv21
     */
    public static byte[] I420Tonv21(byte[] data, int width, int height) {
        byte[] ret = new byte[data.length];
        int total = width * height;
        
        ByteBuffer bufferY = ByteBuffer.wrap(ret, 0, total);
        ByteBuffer bufferVU = ByteBuffer.wrap(ret, total, total / 2);
        
        bufferY.put(data, 0, total);
        for (int i = 0; i < total / 4; i += 1) {
            bufferVU.put(data[i + total + total / 4]);
            bufferVU.put(data[total + i]);
        }
        
        return ret;
    }
	
	
	/**
	 * nv21转I420
	 * @param data 
	 * @param width
	 * @param height
	 * @return
	 */
	public static byte[] nv21ToI420(byte[] data, int width, int height) {  
	    byte[] ret = new byte[data.length];  
	    int total = width * height;  
	      
	    ByteBuffer bufferY = ByteBuffer.wrap(ret, 0, total);  
	    ByteBuffer bufferU = ByteBuffer.wrap(ret, total, total / 4);  
	    ByteBuffer bufferV = ByteBuffer.wrap(ret, total + total / 4, total / 4);  
	      
	    bufferY.put(data, 0, total);  
	    for (int i=total; i "+Arrays.toString(data));
			byte[] i420data=nv21ToI420(data,5,4);
			System.out.println("I420 数据  --> "+Arrays.toString(i420data));
			byte[] nv21data=I420Tonv21(i420data,5,4);
			System.out.println("NV21 数据  --> "+Arrays.toString(nv21data));
	}
	

一张图片的大小为widthheight, YUV420图片数据的大小就是widthheight*3/2

NV21 数据格式:
widthheight个字节存的是每个像素的Y分量,后面的widthheight/2字节是VUVUVUVU…
如: YYYY…YYVUVUVUVU…

I420 是数据格式:
widthheight个字节还是每个像素的Y分量,接下来的widthheight/4字节是U分量,最后的width*height/4字节是V分量
如: YYYY…YYUUUUVVVV…

模拟数据测试结果如下:
其中: 1表示是Y, 2表示是U ,3表示是V

NV21 数据 --> [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2]
I420 数据 --> [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
NV21 数据 --> [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2]

你可能感兴趣的:(android,java)