上述RasterIO()的写法可以兼容16为图像的读写,只不过要注意的是buf中是用2个Gbyte来表达1个16像素值的。当然为了更方便图像处理,也可以采用16位整型来读取buf:
//申请buf size_t imgBufNum = (size_t)bufWidth * bufHeight * bandNum; GUInt16 *imgBuf = new GUInt16[imgBufNum]; //读取 img->RasterIO(GF_Read, 0, 0, bufWidth, bufHeight, imgBuf, bufWidth, bufHeight, GDT_UInt16, bandNum, nullptr, bandNum*depth, bufWidth*bandNum*depth, depth); //写入 dst->RasterIO(GF_Write, 0, 0, bufWidth, bufHeight, imgBuf, bufWidth, bufHeight, GDT_UInt16, bandNum, nullptr, bandNum*depth, bufWidth*bandNum*depth, depth); //释放 delete[] imgBuf; imgBuf = nullptr;可以发现,除了要更改buf的容量和RasterIO()的第九个参数GDT_UInt16,其余什么都不需要更改。注意创建16位图像时参数也需要更改成16位:
GDALDataset* dst = pDriver->Create(dstPath, bufWidth, bufHeight, bandNum, GDT_UInt16, ppszOptions); 3.3.读取特定波段某些情况下需要读取特定波段,或者需要重组波段顺序。例如VC中显示图像往往需要将buf按照BGR传递给BITMAP,再显示BITMAP。这时只需要修改第11个参数就行了:
//波段索引 int panBandMap[3] = { 3,2,1 }; //申请buf size_t imgBufNum = (size_t) bufWidth * bufHeight * bandNum * depth; GByte *imgBuf = new GByte[imgBufNum]; //读取 img->RasterIO(GF_Read, 0, 0, bufWidth, bufHeight, imgBuf, bufWidth, bufHeight, GDT_Byte, bandNum, panBandMap, bandNum*depth, bufWidth*bandNum*depth, depth); //写入 dst->RasterIO(GF_Write, 0, 0, bufWidth, bufHeight, imgBuf, bufWidth, bufHeight, GDT_Byte, bandNum, nullptr, bandNum*depth, bufWidth*bandNum*depth, depth); //释放 delete[] imgBuf; imgBuf = nullptr;这时得到的dst.tif为:
3.4.左下角起点读写默认情况RasterIO()是以左上角起点读写的,不过也是可以以左下角为起点读写,只需要重新设置排布buf的位置。这里读写lena图像上同一块位置:
//申请buf size_t imgBufNum = (size_t) bufWidth * bufHeight * bandNum * depth; size_t imgBufOffset = (size_t) bufWidth * (bufHeight-1) * bandNum * depth; GByte *imgBuf = new GByte[imgBufNum]; //读取 img->RasterIO(GF_Read, 0, 0, bufWidth, bufHeight, imgBuf + imgBufOffset, bufWidth, bufHeight, GDT_Byte, bandNum, nullptr, bandNum*depth, -bufWidth*bandNum*depth, depth); //写入 dst->RasterIO(GF_Write, 0, 0, bufWidth, bufHeight, imgBuf + imgBufOffset, bufWidth, bufHeight, GDT_Byte, bandNum, nullptr, bandNum*depth, -bufWidth*bandNum*depth, depth); //释放 delete[] imgBuf; imgBuf = nullptr;注意这里Y方向起点位置,也就是第三个参数仍然要用左上角起算,但是buf已经是左下角起点了。
3.5.重采样读写RasterIO()另外一个用法是可以自动缩放,重采样读写影像,例如这里将512X512大小的lena图像重采样成256X256大小:
//申请buf size_t imgBufNum = (size_t) bufWidth * bufHeight * bandNum * depth; size_t imgBufOffset = (size_t) bufWidth * (bufHeight-1) * bandNum * depth; GByte *imgBuf = new GByte[imgBufNum]; //读取 img->RasterIO(GF_Read, 0, 0, imgWidth, imgHeight, imgBuf + imgBufOffset, bufWidth, bufHeight, GDT_Byte, bandNum, nullptr, bandNum*depth, -bufWidth*bandNum*depth, depth); //写入 dst->RasterIO(GF_Write, 0, 0, bufWidth, bufHeight, imgBuf + imgBufOffset, bufWidth, bufHeight, GDT_Byte, bandNum, nullptr, bandNum*depth, -bufWidth*bandNum*depth, depth); //释放 delete[] imgBuf; imgBuf = nullptr;