#include "stdafx.h"
#include "windows.h"
#include
#include"gdal.h"
#include"gdal_priv.h"
#include"io.h"
#include"cpl_string.h"
#include
#include
using namespace std;
int main(){
//cout << "hello world" << endl;
GDALAllRegister(); //GDAL所有操作都需要先注册格式
CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); //支持中文路径
const char* imgPath = "F:\\gdal\\data\\DOM\\E110D7_N31D3_20170516_GF1_WFV1_DOM2.tif";
GDALDataset* poDataset;
poDataset = (GDALDataset *)GDALOpen(imgPath, GA_ReadOnly);
if (poDataset == nullptr)
{
cout << "Can't Open Image!" << endl;
}
int nBandCount = poDataset->GetRasterCount();
int nImgSizeX = poDataset->GetRasterXSize();
int nImgSizeY = poDataset->GetRasterYSize();
const char *Pro = poDataset->GetProjectionRef();
cout << "图像的宽是" << nImgSizeX << "经度" << endl;
cout << "图像的高是" << nImgSizeY << "纬度" << endl;
cout << "图像的波段数是" << nBandCount << endl;
int xBuff = nImgSizeX;
int YBuff = nImgSizeY;
//申请存储空间
WORD *pBuf = new WORD[nImgSizeX*nImgSizeY*nBandCount];
memset(pBuf, 0, nImgSizeX*nImgSizeY*nBandCount*sizeof(WORD));
//图像读入方式
int panbandmap[4] = { 1, 2, 3, 4 };
poDataset->RasterIO(GF_Read, 0, 0, nImgSizeX, nImgSizeY, pBuf, xBuff, YBuff, GDT_UInt16, nBandCount, panbandmap, 0, 0, 0);
const char *pszFormat = "Gtiff";
GDALDriver*poDriver;
poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat);
if (poDriver == nullptr)
exit(1);
//判断驱动是不是支持Create和CreateCopy函数
char**papszMetadata;
papszMetadata = poDriver->GetMetadata();
if (CSLFetchBoolean(papszMetadata, GDAL_DCAP_CREATE, false))
printf("Driver%s supports Create()method.n\n\n", pszFormat);
if (CSLFetchBoolean(papszMetadata, GDAL_DCAP_CREATECOPY, false))
printf("Driver%s supports CreateCopy()method.n\n\n", pszFormat);
//将图像以CreateCopy的方式写出来
GDALDataset*poDstDS;
const char*imgPath1 = ("F:\\gdal\\data\\DOM1.tif");
poDstDS = poDriver->CreateCopy(imgPath1, poDataset, TRUE, NULL, NULL, NULL);
if (poDstDS != nullptr)
{
printf("copy图像%s成功.\n", imgPath1);
}
delete poDstDS;
//设置图像变换6参数,将图像以RasterIO的方式写出来
double dGeotransform[6];
poDataset->GetGeoTransform(dGeotransform);
GDALDataset*poDstDS1;
const char *imgPath2 = ("F:\\gdal\\data\\DOM2.tif");
poDstDS1 = poDriver->Create(imgPath2, nImgSizeX, nImgSizeY, nBandCount, GDT_UInt16, NULL);
poDstDS1->RasterIO(GF_Write, 0, 0, nImgSizeX, nImgSizeY, pBuf, xBuff, YBuff, GDT_UInt16, nBandCount, panbandmap, 0, 0, 0);
poDstDS1->SetProjection(Pro);
poDstDS1->SetGeoTransform(dGeotransform);
if (poDstDS1 != nullptr)
{
printf("写出图像%s成功.\n", imgPath2);
}
delete[]pBuf;
pBuf = nullptr;
delete poDstDS1;
}