GDALAllRegister();//注册驱动
CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");//中文路径
GDALDataset *poDataset= (GDALDataset *)GDALOpen(fileName, GA_ReadOnly);//得到数据集
wheight = poDataset->GetRasterYSize();//宽
wwidth = poDataset->GetRasterXSize();//高
bandNum = poDataset->GetRasterCount();//波段数
//读取三个波段
GDALRasterBand *pBandR = poDataset->GetRasterBand(1);
GDALRasterBand *pBandG = poDataset->GetRasterBand(2);
GDALRasterBand *pBandB = poDataset->GetRasterBand(3);
wdepth = pBandR->GetRasterDataType();//int wdepth 深度
GDALDataType dataType = pBandR->GetRasterDataType();//类型
//获得波段数值
GByte *pBufR = new GByte[wwidth * wheight * wdepth];
GByte *pBufG = new GByte[wwidth * wheight * wdepth];
GByte *pBufB = new GByte[wwidth * wheight * wdepth];
//16bit时,可以直接传下面三个参数
ushort *pBufRs = new ushort[wwidth * wheight];
ushort *pBufGs = new ushort[wwidth * wheight];
ushort *pBufBs = new ushort[wwidth * wheight];
pBandR->RasterIO(GF_Read, 0, 0, wwidth, wheight, pBufR, wwidth, wheight, dataType, 0, 0);
pBandG->RasterIO(GF_Read, 0, 0, wwidth, wheight, pBufG, wwidth, wheight, dataType, 0, 0);
pBandB->RasterIO(GF_Read, 0, 0, wwidth, wheight, pBufB, wwidth, wheight, dataType, 0, 0);
/*
GByte 对应8bit,;16bit将使用两个byte存储:pBufR[0]和pBufR[1]表示第一个rgb值,通过按位运算融合成一个ushort,此值与遥感软件:envi中对应的data相同,测试与直接传参稍有区别
*/
int j = 0;
ushort s;
if (wdepth > 1)
{
for (int i = 0; i < wwidth * wheight * wdepth; i += wdepth)
{
s = (ushort)(pBufR[i + 1] << 8 | pBufR[i]);
pBufRs[j] = s;
s = (ushort)(pBufG[i + 1] << 8 | pBufG[i]);
pBufGs[j] = s;
s = (ushort)(pBufB[i + 1] << 8 | pBufB[i]);
pBufBs[j++] = s;
}
}
/*
GByte 直接转成ushort,方便调用*/
else
{
for (int i = 0; i < wwidth * wheight; i++)
{
s = (ushort)( pBufR[i]);
pBufRs[j] = s;
s = (ushort)( pBufG[i]);
pBufGs[j] = s;
s = (ushort)( pBufB[i]);
pBufBs[j++] = s;
}
}