1. 程式人生 > >Yuv420轉Jpeg(C語言實現)

Yuv420轉Jpeg(C語言實現)

YUV2Jpg(in_Y,in_U,in_V,0x400,0x1b0,75,0x420,pData,&dwSize); 

     引數說明:in_Y:輸入的420的Y分量;in_U:輸入的420的U分量,in_V:輸入420的V分量;width:表示影象的寬;height表示影象的高;quality表示量化因子,n_Stride表示Yuv的跨度,即Yuv的寬,因為該函式只能處理16的整數倍,所以width為0x400;pOut表示轉化後的資料;pnOutSize為轉化後的jpeg檔案的大小;

int YUV2Jpg(PBYTE in_Y,PBYTE in_U,PBYTE in_V,int width,int

height,int quality,int nStride,PBYTE pOut,DWORD *pnOutSize)  //

{

     PBYTE pYBuf,pUBuf,pVBuf;

     int nYLen = nStride  * height;

     int nUVLen = nStride  * height / 4;

     int  nDataLen;

     JPEGINFO JpgInfo;

     ZeroMemory(&JpgInfo,sizeof(JPEGINFO));

     JpgInfo.bytenew = 0;

     JpgInfo.bytepos = 7;

     pYBuf = (PBYTE)malloc(nYLen);                      //獲取Y的值

     memcpy(pYBuf,in_Y,nYLen);

     pUBuf = (PBYTE)malloc(nYLen);

     pVBuf = (PBYTE)malloc(nYLen);

     ProcessUV(pUBuf,in_U,width,height,nStride);        //獲取U的值

     ProcessUV(pVBuf,in_V,width,height,nStride);        //獲取V

     //  

GetDataFromSource(pYBuf,pUBuf,pVBuf,in_Y,in_U,in_V,width);

     DivBuff(pYBuf,width,height,nStride,DCTSIZE,DCTSIZE);

     DivBuff(pUBuf,width,height,nStride,DCTSIZE,DCTSIZE);

     DivBuff(pVBuf,width,height,nStride,DCTSIZE,DCTSIZE);

     quality = QualityScaling(quality);

     SetQuantTable(std_Y_QT,JpgInfo.YQT, quality); // 設定Y量化表

     SetQuantTable(std_UV_QT,JpgInfo.UVQT,quality); // 設定UV量化表

     InitQTForAANDCT(&JpgInfo);                       // 初始化AA&N需要的量化表

     JpgInfo.pVLITAB=JpgInfo.VLI_TAB + 2048;       // 設定VLI_TAB的別名

     BuildVLITable(&JpgInfo);                         // 計算VLI表 

     nDataLen = 0;

     // 寫入各段

     nDataLen = WriteSOI(pOut,nDataLen);

     nDataLen = WriteAPP0(pOut,nDataLen);

     nDataLen = WriteDQT(&JpgInfo,pOut,nDataLen);

     nDataLen = WriteSOF(pOut,nDataLen,width,height);

     nDataLen = WriteDHT(pOut,nDataLen);

     nDataLen = WriteSOS(pOut,nDataLen);

     // 計算Y/UV訊號的交直分量的huffman表,這裡使用標準的huffman表,並不是計算得出,缺點是檔案略長,但是速度快

     BuildSTDHuffTab(STD_DC_Y_NRCODES,STD_DC_Y_VALUES,JpgInfo.STD_DC_Y_HT);

     BuildSTDHuffTab(STD_AC_Y_NRCODES,STD_AC_Y_VALUES,JpgInfo.STD_AC_Y_HT);

     BuildSTDHuffTab(STD_DC_UV_NRCODES,STD_DC_UV_VALUES,JpgInfo.STD_DC_UV_HT);

     BuildSTDHuffTab(STD_AC_UV_NRCODES,STD_AC_UV_VALUES,JpgInfo.STD_AC_UV_HT);

     // 處理單元資料

     nDataLen = ProcessData(&JpgInfo,pYBuf,pUBuf,pVBuf,width,height,pOut,nDataLen); 

     nDataLen = WriteEOI(pOut,nDataLen);

     free(pYBuf);

     free(pUBuf);

     free(pVBuf);

     *pnOutSize = nDataLen;

     return 0;

}

具體程式碼參考YUV2Jpg程式;