1.GDAL库和GeoTIFF文件
GDAL库是处理地理信息数据的开源库。提供了一系列工具和API,供开发者能够读取、转换、写入和处理多种栅格和矢量地理空间数据格式。
GDAL提供了C++、Python、Java、C#等多种编程语言的API,使开发者能够在不同的编程环境中使用GDAL的功能。
tiff格式图片文件就是一种特殊的图片格式,与png、jpg相同。在遥感领域的影像很多都是tif格式存储的,而带有地理信息的tiff文件即可以认为是GeoTIFF
2.VS2022配置GDAL环境(C#),测试读取tiff图片
VS2022工具–NuGet包管理器–管理解决方案的NuGet程序包,直接安装GDAL包。
并且直接用应用到当前的控制台程序中。
找一张tiff格式的图片,或者用格式转换网站:https://www.zamzar.com/.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OSGeo.GDAL;
namespace GDAL_test
{
internal class Program
{
static void Main(string[] args)
{
//使用之前必须要配置、注册
GdalConfiguration.ConfigureGdal();
GdalConfiguration.ConfigureOgr();
Gdal.AllRegister();
string tiffFilePath = "D:\\Users\\59723\\Desktop\\su7.tiff";
// Open函数返回了Dataset类型的对象,相当于实例化
Dataset dataset = Gdal.Open(tiffFilePath, Access.GA_ReadOnly);
if(dataset == null )
{
Console.WriteLine("无法打开文件");
return;
}
// 获取图像信息
int rasterCount = dataset.RasterCount;
int width = dataset.RasterXSize;
int height = dataset.RasterYSize;
Console.WriteLine($"宽度:{
width},高度:{
height},波段数:{
rasterCount}");
// 读取第一个波段
Band band = dataset.GetRasterBand(1);
if( band == null )
{
Console.WriteLine("无法读取波段");
return ;
}
// 这个地方被坑了好久,新版本的ComputeRasterMinMax(double[] argout, int approx_ok),已经没有out入参关键字了
double[] minMax = {
0, 0 };
band.ComputeRasterMinMax(minMax, 0);
Console.WriteLine($"最小值: {
minMax[0]}, 最大值: {
minMax[1]}");
// 读取波段数据
// 在堆区开辟了一个float[]类型的数组变量,大小为width * height图片像素
float[] rasterData = new float[width * height];
// 参数1-2:左上角位置,参数3-4:目标区域大小,参数5:接收容器,参数6-7:容器的宽高,参数8-9:默认0
band.ReadRaster(0, 0, width, height, rasterData, width, height, 0, 0);
// 处理波段数据 (例如,打印前10个像素值)
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"像素值[{
i}]: {
rasterData[i]}");
}
dataset.Dispose();
Console.ReadKey();
}
}
}
3.读取GeoTiff图片并提取相关地理信息
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OSGeo.GDAL;
namespace GDAL_Geotiff
{
internal class Program
{
static void Main(string[] args)
{
GdalConfiguration.ConfigureGdal();
Gdal.AllRegister();
string geotiff_file_path = "D:\\Users\\59723\\Desktop\\landscan-global-2022-colorized.tif";
Dataset dataset = Gdal.Open(geotiff_file_path, Access.GA_ReadOnly);
if(dataset == null )
{
Console.WriteLine("无法打开!");
return;
}
Console.WriteLine("投影信息:");
Console.WriteLine(dataset.GetProjection());
//Console.ReadKey();
double[] geoTransform = new double[6];
dataset.GetGeoTransform(geoTransform);
Console.WriteLine("地理变换参数:");
Console.WriteLine("左上角X:" + geoTransform[0]);
Console.WriteLine("像素宽度: " + geoTransform[1]);
Console.WriteLine("旋转参数: " + geoTransform[2]);
Console.WriteLine("左上角Y: " + geoTransform[3]);
Console.WriteLine(