GDAL基本操作代码笔记

#include "gdal_priv.h"
#include 

using namespace std;
int main()
{
	//注册文件格式
	GDALAllRegister();
	CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");  //supporting for chinese

	const char* pszFile1 = "E:\\data\\tifimg\\tiftest1.TIF";
	const char* pszFile2 = "E:\\data\\tifimg\\tiftest2.TIF";
	const char* pszFile3 = "E:\\data\\tifimg\\tiftest3.TIF";

	//使用只读方式打开图像
	GDALDataset *poDataset = (GDALDataset*)GDALOpen(pszFile1, GA_ReadOnly);
	GDALDataset *poDataset2 = (GDALDataset*)GDALOpen(pszFile2, GA_ReadOnly);
	GDALDataset *poDataset3 = (GDALDataset*)GDALOpen(pszFile3, GA_ReadOnly);

	if (poDataset == NULL )
	{
		cout << "File:" << pszFile1 <<"Can not open!"<< endl;
		return 0;
	}

	int imgWidth = poDataset->GetRasterXSize();   //图像宽度
	int imgHeight = poDataset->GetRasterYSize();  //图像高度
	int bandNum = poDataset->GetRasterCount();    //波段数
	int depth = GDALGetDataTypeSize(poDataset->GetRasterBand(1)->GetRasterDataType()) / 8;    //图像深度

	//输出影像格式信息
	cout << "Driver: " << poDataset->GetDriver()->GetDescription()<< "  "<< poDataset->GetDriver()->GetMetadataItem(GDAL_DMD_LONGNAME)<GetRasterXSize() << "  " << poDataset->GetRasterYSize() << " " << poDataset->GetRasterCount() << endl;

	//输出影像投影信息
	if (poDataset->GetProjectionRef()!=NULL)
	{
		cout << "Projection is: " << poDataset->GetProjectionRef() << endl;
	}

	//输出图像的坐标和分辨率信息
	double adfGeoTransform[6];
	if (poDataset->GetGeoTransform(adfGeoTransform) == CE_None)
	{
		cout << "Origin = (" << adfGeoTransform[0] << "," << adfGeoTransform[3] << ")" << endl;
		cout << "PixelSize = (" << adfGeoTransform[1] << "," << adfGeoTransform[5] << ")" << endl;
	}

	//read a block of the img,  starting from (2000,2000), size of 1000*1000
	int bufWidth = 1000;
	int bufHeight = 1000;
	int left_up_x = 2000;
	int left_up_y = 2000;
	//申请buf
	size_t imgBufNum = (size_t)bufWidth * bufHeight * bandNum * depth;
	GByte *imgBuf = new GByte[imgBufNum];

	//参数意义依次,读写操作,起点,块大小,读写指针,缓冲区大小,数据类型,波段数,需要处理的波段序号(数组),X方向上两个相邻象素之间的字节偏移,y方向上相邻两行之间的字节偏移,相邻两波段之间的字节偏移
	poDataset->RasterIO(GF_Read, left_up_x, left_up_y, bufWidth, bufHeight, imgBuf, bufWidth, bufHeight, GDT_Byte, bandNum, nullptr,bandNum*depth, bufWidth*bandNum*depth, depth);

	//save the block as an img 
	GDALDriver *pDriver = GetGDALDriverManager()->GetDriverByName("GTIFF"); //图像驱动

	char** ppszOptions = NULL;
	ppszOptions = CSLSetNameValue(ppszOptions, "BIGTIFF", "IF_NEEDED"); //配置图像信息
	const char* blockPath = "E:\\data\\block.tif";

	GDALDataset* block = pDriver->Create(blockPath, bufWidth, bufHeight, 1, GDT_Byte, ppszOptions);
	if (block == nullptr)
	{
		printf("Can't Write Image!");
		return false;
	}

	//写入
	block->RasterIO(GF_Write, 0, 0, bufWidth, bufHeight, imgBuf, bufWidth, bufHeight, GDT_Byte, bandNum, nullptr, bandNum*depth, bufWidth*bandNum*depth, depth);

	//释放
	delete []imgBuf;
	imgBuf = nullptr;

	//close the img
	GDALClose(poDataset);
	GDALClose(block);

	return 0;
}

 

你可能感兴趣的:(GDAL基本操作代码笔记)