gdal解析tif

bool HandleTif::ReadTif()
{
	//tif文件读取
	std::string name = "D:\\XX\\xx.tif";
	const char *charName = name.c_str();
	//注册
	GDALAllRegister();
	//以防中文名不能正常读取
	CPLSetConfigOption("GDAL_FILENAME_IS_UTF8","NO");
	GDALDataset *m_pDataset = (GDALDataset*)GDALOpen(charName, GA_ReadOnly);
	//获取第1波段的波段指针,参数就是表示第几波段的意思  
	if(m_pDataset==NULL)
	{
		AfxMessageBox("读取图像失败!");
		return FALSE;
	}
	int Width = m_pDataset->GetRasterXSize(); //获取图像宽
	int Height = m_pDataset->GetRasterYSize(); //获取图像高
	int Count = m_pDataset->GetRasterCount(); //波段数

	//读取数据
	GDALRasterBand  *pInRasterBand = m_pDataset->GetRasterBand(1);
	float *inBuf;
	inBuf = new float[Width*Height];
	ZeroMemory(inBuf,sizeof(float)*Width*Height);
	CPLErr err;
	err=pInRasterBand->RasterIO(GF_Read,0,0,Width,Height,inBuf,Width,Height,GDT_Float32,0,0);

	if(err==CE_Failure)
	{
		AfxMessageBox("读取输入图像数据失败!");
		return FALSE;
	}

	//创建输出图像、写图像
	CString outPath("C:\\Users\\Administrator\\Desktop\\xx.tif");
	GDALDriver *poDriver =GetGDALDriverManager()->GetDriverByName("GTiff");
	if( poDriver==NULL)
	{
		AfxMessageBox("获取创建输出图像指针poDriver失败!");
		return FALSE;
	}

	CString OutFilename = CString(outPath);
	OutFilename.TrimRight();
	GDALDataset* pOutDataset=poDriver->Create(OutFilename,Width,Height,1,GDT_Float32,NULL);
	if(pOutDataset == NULL)
	{
		AfxMessageBox("create输出图像失败!");
		return FALSE;
	}
	GDALRasterBand* pOutRasterBand = pOutDataset->GetRasterBand(1);

	err = pOutRasterBand->RasterIO(GF_Write,0,0,Width,Height,inBuf,Width,Height,GDT_Float32,0,0);
	if(err==CE_Failure)
	{
		AfxMessageBox("输出图像写失败!");
		return FALSE;
	}

	//关闭波段和驱动
	GDALClose(m_pDataset);
	GDALClose(pOutDataset);
	GetGDALDriverManager()->DeregisterDriver(poDriver);
	GDALDestroyDriverManager();
	return true;
}

gdal库环境配置:https://malagis.com/win7-vs2010-gdal.html

gdal项目配置:https://malagis.com/vs2010-project-configuration-gdal.html

arcgis安装:https://malagis.com/arcgis-desktop-10-4-1-full-installation-tutorial.html

你可能感兴趣的:(C++,C,tif,gdal)