1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| void GDALBlockReadWrite(string openFilePath, string saveFilePath, int nBlockSize) { GDALDataset *poSrcDS = (GDALDataset*)GDALOpen(openFilePath.c_str(), GA_ReadOnly); if (poSrcDS == NULL) return ;
int nXSize = poSrcDS->GetRasterXSize(); int nYSize = poSrcDS->GetRasterYSize(); int nBands = poSrcDS->GetRasterCount();
double adfGeotransform[6] = { 0 }; poSrcDS->GetGeoTransform(adfGeotransform);
const char* pszProj = poSrcDS->GetProjectionRef();
GDALRasterBand *poBand = poSrcDS->GetRasterBand(1); if (poBand == NULL) { GDALClose((GDALDatasetH)poSrcDS); return ; } int dataType = poBand->GetRasterDataType();
string format = "GTiff"; GDALDriver *saveDriver = GetGDALDriverManager()->GetDriverByName(format.c_str()); GDALDataset *saveDataset = saveDriver->Create(saveFilePath.c_str(), nXSize, nYSize, nBands, GDT_Float32, NULL); saveDataset->SetGeoTransform(adfGeotransform); saveDataset->SetProjection(pszProj);
float *pafScan = new float[nBlockSize*nBlockSize*nBands];
int *pBandMaps = new int[nBands]; for (int i = 0; i < nBands; i++) pBandMaps[i] = i + 1;
for (int r = 0; r < nYSize; r += nBlockSize) { for (int c = 0; c < nXSize; c += nBlockSize) { int nXBlock = nBlockSize; int nYBlock = nBlockSize;
if (r + nBlockSize > nYSize) nYBlock = nYSize - r; if (c + nBlockSize > nXSize) nXBlock = nXSize - c;
poSrcDS->RasterIO(GF_Read, c, r, nXBlock, nYBlock, pafScan, nXBlock, nYBlock, GDT_Float32, nBands, pBandMaps, 0, 0, 0, NULL); saveDataset->RasterIO(GF_Write, c, r, nXBlock, nYBlock, pafScan, nXBlock, nYBlock, GDT_Float32, nBands, 0, 0, 0, 0); GDALFlushCache(saveDataset); } }
delete[]pBandMaps; delete[]pafScan; GDALClose((GDALDatasetH)poSrcDS); }
|