I'm a rookie in GDAL and C++. I tried to copy the red band of the RGB tif file with Create() and GetRasterBand(1)->RasterIO(). I got the right size of my new tif file, but all the value of the new image is 128. I tried to check the value while it run, and I'm sure they have the same value in the red band of the RGB TIFF file. I guessed there is something wrong in the GetRasterBand(1)->RasterIO(). However, I still have no idea after checking the document.
This project need to run with the Visual Studio 2008 on Win10, so I used the version 2.2.3 of GDAL.
#include "stdafx.h"
#include "stdio.h"
#include "gdal.h"
#include "gdal_priv.h"
#include "cpl_conv.h" //for CPLMalloc()
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) {
//Register GDAL
GDALAllRegister();
//image file input_file
const char* input = "C:\\Users\\GOLiF\\Documents\\Visual Studio 2008\\Projects\\GDAL_223\\GDAL_223\\94212060_20190924_109EMAP.tif";
const char* output = "C:\\Users\\GOLiF\\Documents\\Visual Studio 2008\\Projects\\GDAL_223\\GDAL_223\\test.tif";
GDALDataset *pOldDS, *pNewDS ;
GDALDriver *pDriverTiff ;
int nRows, nCols ;
double transform[6] ;
double noData ;
pOldDS = (GDALDataset*) GDALOpen( input, GA_ReadOnly ) ;
nRows = pOldDS ->GetRasterBand(1) ->GetYSize() ;
nCols = pOldDS ->GetRasterBand(1) ->GetXSize() ;
noData = pOldDS ->GetRasterBand(1) ->GetNoDataValue() ;
pOldDS ->GetGeoTransform(transform) ;
pDriverTiff = GetGDALDriverManager()->GetDriverByName("GTiff") ;
pNewDS = pDriverTiff->Create( output, nCols, nRows, 1, GDT_Int16, NULL) ;
pNewDS->SetGeoTransform(transform) ;
pNewDS->GetRasterBand(1)->SetNoDataValue(noData) ;
short *oldRow = (short *) CPLMalloc(sizeof(short)*nCols) ;
short *newRow = (short *) CPLMalloc(sizeof(short)*nCols) ;
for (int i = 0 ; i < nRows ; i++){
pOldDS->GetRasterBand(1)->RasterIO(GF_Read, 0, i, nCols, 1, oldRow, nCols, 1, GDT_Int16, 0, 0) ;
for (int j = 0 ; j < nCols ; j++){
if (oldRow[j] == noData ){
newRow[j] = noData ;
//cout << "nodata : newrow[" << j << "] = " << newrow[j] << endl;
//system("pause");
}
else{
newRow[j] = oldRow[j] ;
//cout << "oldrow[" << j << " ]= " << oldRow[j] << endl;
//cout << "newrow[" << j << " ]= " << newRow[j] << endl;
//system("pause");
}
}
pNewDS->GetRasterBand(1)->RasterIO(GF_Write, 0, i, nCols, 1, newRow, nCols, 1, GDT_Int16, 0, 0) ;
//cout << "newrow= " << &newRow << endl;
}
GDALClose(pOldDS);
GDALClose(pNewDS);
system("pause");
}