GDAL保存图像某一波段

void example02()
{
	GDALAllRegister();
	CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");

	//读取图像
	const char* pszFilename = "C:\\Qt\\1.tif";
	GDALDataset* dataset = (GDALDataset*)GDALOpen(pszFilename, GA_ReadOnly);
	if (!dataset)
		return;

	int width = dataset->GetRasterXSize();
	int height = dataset->GetRasterYSize();
	int band = dataset->GetRasterCount();
	int depth = GDALGetDataTypeSize(dataset->GetRasterBand(1)->GetRasterDataType()) / 8;

	size_t size = width * height * band * depth;
	GByte* buffer = new GByte[size];
	dataset->RasterIO(
		GF_Read,
		0, 0, width, height,
		buffer, width, height, GDT_Byte, band, nullptr,
		band*depth, width*band*depth, depth
	);

	//写入图像
	GDALDriver *driver = GetGDALDriverManager()->GetDriverByName("GTIFF");
	char** ppszOptions = nullptr;
	CSLSetNameValue(ppszOptions, "BIGTIFF", "IF_NEEDED");
	const char* psz_name = "C:\\Qt\\target.tif";
	GDALDataset* target_dataset = driver->Create(psz_name, width, height, 1, GDT_Byte, ppszOptions);
	if (!target_dataset)
		return;

	int pan_band_map[] = { 1 };

	target_dataset->RasterIO(
		GF_Write,
		0, 0, width, height,
		buffer, width, height, GDT_Byte, 1, pan_band_map,
		band*depth, width*band*depth, depth
	);

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

	GDALClose(target_dataset);
}
posted @ 2021-08-24 10:46  暹罗吹雪  阅读(188)  评论(0编辑  收藏  举报