Project address: https://github.com/OSGeo/gdal
API overview documentation: https://gdal.org/en/stable/api/index.html
C/C++ API reference: https://gdal.org/en/stable/api/index.html#c-api
Python API reference: https://gdal.org/en/stable/api/python/index.html
Java API reference: https://gdal.org/en/stable/api/java/index.html
C# API reference: https://gdal.org/en/stable/api/csharp/index.html
License: MIT License
Overview
GDAL is the de facto standard library for geospatial data processing, maintained by the OSGeo Foundation. It provides:
- 200+ raster drivers: GeoTIFF, NetCDF, HDF5, COG, JPEG2000, etc.
- 100+ vector drivers: Shapefile, GeoJSON, GeoPackage, PostGIS, FlatGeobuf, etc.
- Coordinate reference systems: PROJ-based coordinate transformation and projection conversion
- Raster analysis: resampling, mosaicking, clipping, band math, DEM analysis, etc.
- Vector operations: spatial filtering, attribute queries, feature creation and editing, etc.
GDAL's core is implemented in C++, and it also provides through SWIG Python、Java、C# three language bindings, with each language API maintaining class and method naming consistent with C++.
Environment preparation
C++ environment
# Linux (Debian/Ubuntu)
apt-get install libgdal-dev
# macOS (Homebrew)
brew install gdal
# CMake 项目中链接 GDAL
# CMakeLists.txt
find_package(GDAL REQUIRED)
target_link_libraries(myapp PRIVATE GDAL::GDAL)
Python environment
# pip 安装(需系统已安装 GDAL 库)
pip install gdal
# Conda 安装(推荐,自动处理 C 库依赖)
conda install -c conda-forge gdal
# 验证
python -c "from osgeo import gdal; print(gdal.VersionInfo())"
Java environment
<!-- Maven 依赖 -->
<dependency>
<groupId>org.gdal</groupId>
<artifactId>gdal</artifactId>
<version>3.10.0</version>
</dependency>
// Gradle
implementation 'org.gdal:gdal:3.10.0'
Note: The Java bindings require finding the PATH(Windows) or LD_LIBRARY_PATH(Linux) in the system gdalalljni native library.
C# environment
# .NET Core / .NET 5+ 项目
dotnet add package MaxRev.Gdal.Core
dotnet add package MaxRev.Gdal.LinuxRuntime.Minimal # Linux
dotnet add package MaxRev.Gdal.WindowsRuntime.Minimal # Windows
Note: The official SWIG binding namespace is OSGeo.GDAL、OSGeo.OGR、OSGeo.OSR. The NuGet package MaxRev.Gdal.Core is a community-maintained cross-platform wrapper.
Core classes at a glance
The GDAL API maintains a consistent class structure across the four languages. The following table lists the core classes and their purposes:
Core classes of the raster API
| Class | C++ header / module | Purpose |
|---|---|---|
GDALDriver |
gdal_priv.h / osgeo.gdal |
Raster driver—register formats, create datasets |
GDALDataset |
gdal_priv.h / osgeo.gdal |
★ Raster dataset—open, read/write, retrieve metadata |
GDALRasterBand |
gdal_priv.h / osgeo.gdal |
Raster band—read/write pixels, retrieve statistics |
GDALColorTable |
gdal_priv.h / osgeo.gdal |
Color table—indexed color mapping |
GDALRasterAttributeTable |
gdal_priv.h / osgeo.gdal |
Raster attribute table |
Core classes of the vector API (OGR)
| Class | C++ header / module | Purpose |
|---|---|---|
OGRSFDriver / GDALDriver |
ogrsf_frmts.h / osgeo.ogr |
Vector driver |
GDALDataset / OGRDataSource |
ogrsf_frmts.h / osgeo.ogr |
★ Vector data source—manage layer collections |
OGRLayer |
ogrsf_frmts.h / osgeo.ogr |
★ Vector layer—read/write features, spatial filtering |
OGRFeature |
ogr_feature.h / osgeo.ogr |
Vector feature—attributes + geometry |
OGRFeatureDefn |
ogr_feature.h / osgeo.ogr |
Feature definition—field structure |
OGRFieldDefn |
ogr_feature.h / osgeo.ogr |
Field definition—name, type |
OGRGeometry |
ogr_geometry.h / osgeo.ogr |
Geometry base classes (Point, LineString, Polygon, etc.) |
Spatial reference classes (OSR)
| Class | C++ header / module | Purpose |
|---|---|---|
OGRSpatialReference |
ogr_spatialref.h / osgeo.osr |
★ Spatial reference system—define CRS |
OGRCoordinateTransformation |
ogr_spatialref.h / osgeo.osr |
★ Coordinate transformation—convert coordinates between different CRSs |
Comparison of modules / namespaces by language
| Functional domain | C++ | Python | Java | C# |
|---|---|---|---|---|
| Raster | #include "gdal_priv.h" |
from osgeo import gdal |
import org.gdal.gdal.* |
using OSGeo.GDAL; |
| Vector | #include "ogrsf_frmts.h" |
from osgeo import ogr |
import org.gdal.ogr.* |
using OSGeo.OGR; |
| Spatial Reference | #include "ogr_spatialref.h" |
from osgeo import osr |
import org.gdal.osr.* |
using OSGeo.OSR; |
Raster Data Reading
C++
#include "gdal_priv.h"
GDALAllRegister();
GDALDataset *ds = (GDALDataset *)GDALOpen("dem.tif", GA_ReadOnly);
if (ds == nullptr) { /* 错误处理 */ }
// 基本信息
int width = ds->GetRasterXSize();
int height = ds->GetRasterYSize();
int bands = ds->GetRasterCount();
// 仿射变换参数 [左上X, 像素宽度, 旋转, 左上Y, 旋转, 像素高度(负)]
double gt[6];
ds->GetGeoTransform(gt);
// 投影信息
const char *proj = ds->GetProjectionRef();
// 读取第一个波段
GDALRasterBand *band = ds->GetRasterBand(1);
float *buf = new float[width * height];
band->RasterIO(GF_Read, 0, 0, width, height, buf, width, height, GDT_Float32, 0, 0);
// 获取 NoData 值
int hasNoData;
double nodata = band->GetNoDataValue(&hasNoData);
delete[] buf;
GDALClose(ds);
Python
from osgeo import gdal
ds = gdal.Open("dem.tif", gdal.GA_ReadOnly)
if ds is None:
raise RuntimeError("无法打开文件")
# 基本信息
width = ds.RasterXSize
height = ds.RasterYSize
bands = ds.RasterCount
# 仿射变换参数
gt = ds.GetGeoTransform()
# 投影信息
proj = ds.GetProjection()
# 读取第一个波段为 NumPy 数组
band = ds.GetRasterBand(1)
data = band.ReadAsArray() # numpy.ndarray
# 获取 NoData 值
nodata = band.GetNoDataValue()
ds = None # 关闭数据集
Java
import org.gdal.gdal.gdal;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.Band;
import org.gdal.gdalconst.gdalconstConstants;
gdal.AllRegister();
Dataset ds = gdal.Open("dem.tif", gdalconstConstants.GA_ReadOnly);
if (ds == null) { throw new RuntimeException("无法打开文件"); }
// 基本信息
int width = ds.getRasterXSize();
int height = ds.getRasterYSize();
int bands = ds.getRasterCount();
// 仿射变换参数
double[] gt = new double[6];
ds.GetGeoTransform(gt);
// 投影信息
String proj = ds.GetProjection();
// 读取第一个波段
Band band = ds.GetRasterBand(1);
float[] buf = new float[width * height];
band.ReadRaster(0, 0, width, height, buf);
// 获取 NoData 值
Double[] nodata = new Double[1];
band.GetNoDataValue(nodata);
ds.delete();
C#
using OSGeo.GDAL;
Gdal.AllRegister();
Dataset ds = Gdal.Open("dem.tif", Access.GA_ReadOnly);
if (ds == null) { throw new Exception("无法打开文件"); }
// 基本信息
int width = ds.RasterXSize;
int height = ds.RasterYSize;
int bands = ds.RasterCount;
// 仿射变换参数
double[] gt = new double[6];
ds.GetGeoTransform(gt);
// 投影信息
string proj = ds.GetProjection();
// 读取第一个波段
Band band = ds.GetRasterBand(1);
float[] buf = new float[width * height];
band.ReadRaster(0, 0, width, height, buf, width, height, 0, 0);
// 获取 NoData 值
double nodata;
int hasNoData;
band.GetNoDataValue(out nodata, out hasNoData);
ds.Dispose();
Raster Data Creation and Writing
C++
#include "gdal_priv.h"
GDALAllRegister();
GDALDriver *driver = GetGDALDriverManager()->GetDriverByName("GTiff");
GDALDataset *ds = driver->Create("output.tif", 256, 256, 1, GDT_Float32, nullptr);
// 设置仿射变换
double gt[6] = {116.0, 0.01, 0, 40.0, 0, -0.01};
ds->SetGeoTransform(gt);
// 设置投影
OGRSpatialReference srs;
srs.SetWellKnownGeogCS("WGS84");
char *wkt = nullptr;
srs.exportToWkt(&wkt);
ds->SetProjection(wkt);
CPLFree(wkt);
// 写入像素数据
GDALRasterBand *band = ds->GetRasterBand(1);
float *data = new float[256 * 256];
for (int i = 0; i < 256 * 256; i++) data[i] = (float)i;
band->RasterIO(GF_Write, 0, 0, 256, 256, data, 256, 256, GDT_Float32, 0, 0);
band->SetNoDataValue(-9999.0);
delete[] data;
GDALClose(ds);
Python
from osgeo import gdal, osr
import numpy as np
driver = gdal.GetDriverByName("GTiff")
ds = driver.Create("output.tif", 256, 256, 1, gdal.GDT_Float32)
# 设置仿射变换
ds.SetGeoTransform([116.0, 0.01, 0, 40.0, 0, -0.01])
# 设置投影
srs = osr.SpatialReference()
srs.SetWellKnownGeogCS("WGS84")
ds.SetProjection(srs.ExportToWkt())
# 写入 NumPy 数组
band = ds.GetRasterBand(1)
data = np.arange(256 * 256, dtype=np.float32).reshape(256, 256)
band.WriteArray(data)
band.SetNoDataValue(-9999.0)
ds.FlushCache()
ds = None
Java
import org.gdal.gdal.gdal;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.Driver;
import org.gdal.gdal.Band;
import org.gdal.osr.SpatialReference;
gdal.AllRegister();
Driver driver = gdal.GetDriverByName("GTiff");
Dataset ds = driver.Create("output.tif", 256, 256, 1, org.gdal.gdalconst.gdalconstConstants.GDT_Float32);
// 设置仿射变换
ds.SetGeoTransform(new double[]{116.0, 0.01, 0, 40.0, 0, -0.01});
// 设置投影
SpatialReference srs = new SpatialReference();
srs.SetWellKnownGeogCS("WGS84");
ds.SetProjection(srs.ExportToWkt());
// 写入像素数据
Band band = ds.GetRasterBand(1);
float[] data = new float[256 * 256];
for (int i = 0; i < data.length; i++) data[i] = (float) i;
band.WriteRaster(0, 0, 256, 256, data);
band.SetNoDataValue(-9999.0);
ds.FlushCache();
ds.delete();
C#
using OSGeo.GDAL;
using OSGeo.OSR;
Gdal.AllRegister();
Driver driver = Gdal.GetDriverByName("GTiff");
Dataset ds = driver.Create("output.tif", 256, 256, 1, DataType.GDT_Float32, null);
// 设置仿射变换
ds.SetGeoTransform(new double[] { 116.0, 0.01, 0, 40.0, 0, -0.01 });
// 设置投影
SpatialReference srs = new SpatialReference("");
srs.SetWellKnownGeogCS("WGS84");
string wkt;
srs.ExportToWkt(out wkt);
ds.SetProjection(wkt);
// 写入像素数据
Band band = ds.GetRasterBand(1);
float[] data = new float[256 * 256];
for (int i = 0; i < data.Length; i++) data[i] = (float)i;
band.WriteRaster(0, 0, 256, 256, data, 256, 256, 0, 0);
band.SetNoDataValue(-9999.0);
ds.FlushCache();
ds.Dispose();
Vector Data Reading
C++
#include "ogrsf_frmts.h"
GDALAllRegister();
GDALDataset *ds = (GDALDataset *)GDALOpenEx("cities.shp", GDAL_OF_VECTOR, nullptr, nullptr, nullptr);
if (ds == nullptr) { /* 错误处理 */ }
OGRLayer *layer = ds->GetLayer(0);
layer->ResetReading();
OGRFeature *feature;
while ((feature = layer->GetNextFeature()) != nullptr) {
// 读取属性
const char *name = feature->GetFieldAsString("NAME");
int pop = feature->GetFieldAsInteger("POPULATION");
// 读取几何
OGRGeometry *geom = feature->GetGeometryRef();
if (geom != nullptr && wkbFlatten(geom->getGeometryType()) == wkbPoint) {
OGRPoint *pt = (OGRPoint *)geom;
double x = pt->getX();
double y = pt->getY();
}
OGRFeature::DestroyFeature(feature);
}
GDALClose(ds);
Python
from osgeo import ogr
ds = ogr.Open("cities.shp", 0) # 0 = 只读
if ds is None:
raise RuntimeError("无法打开数据源")
layer = ds.GetLayer(0)
for feature in layer:
# 读取属性
name = feature.GetField("NAME")
pop = feature.GetField("POPULATION")
# 读取几何
geom = feature.GetGeometryRef()
if geom is not None and geom.GetGeometryType() == ogr.wkbPoint:
x = geom.GetX()
y = geom.GetY()
ds = None
Java
import org.gdal.ogr.ogr;
import org.gdal.ogr.DataSource;
import org.gdal.ogr.Layer;
import org.gdal.ogr.Feature;
import org.gdal.ogr.Geometry;
ogr.RegisterAll();
DataSource ds = ogr.Open("cities.shp", false); // false = 只读
if (ds == null) { throw new RuntimeException("无法打开数据源"); }
Layer layer = ds.GetLayer(0);
Feature feature;
while ((feature = layer.GetNextFeature()) != null) {
// 读取属性
String name = feature.GetFieldAsString("NAME");
int pop = feature.GetFieldAsInteger("POPULATION");
// 读取几何
Geometry geom = feature.GetGeometryRef();
if (geom != null && geom.GetGeometryType() == ogr.wkbPoint) {
double x = geom.GetX(0);
double y = geom.GetY(0);
}
feature.delete();
}
ds.delete();
C#
using OSGeo.OGR;
Ogr.RegisterAll();
DataSource ds = Ogr.Open("cities.shp", 0); // 0 = 只读
if (ds == null) { throw new Exception("无法打开数据源"); }
Layer layer = ds.GetLayerByIndex(0);
Feature feature;
while ((feature = layer.GetNextFeature()) != null) {
// 读取属性
string name = feature.GetFieldAsString("NAME");
int pop = feature.GetFieldAsInteger("POPULATION");
// 读取几何
Geometry geom = feature.GetGeometryRef();
if (geom != null && geom.GetGeometryType() == wkbGeometryType.wkbPoint) {
double x = geom.GetX(0);
double y = geom.GetY(0);
}
feature.Dispose();
}
ds.Dispose();
Vector Data Creation and Writing
C++
#include "ogrsf_frmts.h"
GDALAllRegister();
GDALDriver *driver = GetGDALDriverManager()->GetDriverByName("ESRI Shapefile");
GDALDataset *ds = driver->Create("output.shp", 0, 0, 0, GDT_Unknown, nullptr);
// 创建图层
OGRSpatialReference srs;
srs.SetWellKnownGeogCS("WGS84");
OGRLayer *layer = ds->CreateLayer("output", &srs, wkbPoint, nullptr);
// 定义字段
OGRFieldDefn nameField("NAME", OFTString);
nameField.SetWidth(64);
layer->CreateField(&nameField);
OGRFieldDefn popField("POPULATION", OFTInteger);
layer->CreateField(&popField);
// 创建要素
OGRFeature *feature = OGRFeature::CreateFeature(layer->GetLayerDefn());
feature->SetField("NAME", "Beijing");
feature->SetField("POPULATION", 21540000);
OGRPoint pt;
pt.setX(116.4);
pt.setY(39.9);
feature->SetGeometry(&pt);
layer->CreateFeature(feature);
OGRFeature::DestroyFeature(feature);
GDALClose(ds);
Python
from osgeo import ogr, osr
driver = ogr.GetDriverByName("ESRI Shapefile")
ds = driver.CreateDataSource("output.shp")
# 创建图层
srs = osr.SpatialReference()
srs.SetWellKnownGeogCS("WGS84")
layer = ds.CreateLayer("output", srs, ogr.wkbPoint)
# 定义字段
layer.CreateField(ogr.FieldDefn("NAME", ogr.OFTString))
layer.CreateField(ogr.FieldDefn("POPULATION", ogr.OFTInteger))
# 创建要素
feature = ogr.Feature(layer.GetLayerDefn())
feature.SetField("NAME", "Beijing")
feature.SetField("POPULATION", 21540000)
pt = ogr.Geometry(ogr.wkbPoint)
pt.SetPoint_2D(0, 116.4, 39.9)
feature.SetGeometry(pt)
layer.CreateFeature(feature)
feature = None
ds = None
Java
import org.gdal.ogr.*;
import org.gdal.osr.SpatialReference;
ogr.RegisterAll();
Driver driver = ogr.GetDriverByName("ESRI Shapefile");
DataSource ds = driver.CreateDataSource("output.shp");
// 创建图层
SpatialReference srs = new SpatialReference();
srs.SetWellKnownGeogCS("WGS84");
Layer layer = ds.CreateLayer("output", srs, ogr.wkbPoint);
// 定义字段
FieldDefn nameField = new FieldDefn("NAME", ogr.OFTString);
nameField.SetWidth(64);
layer.CreateField(nameField);
FieldDefn popField = new FieldDefn("POPULATION", ogr.OFTInteger);
layer.CreateField(popField);
// 创建要素
Feature feature = new Feature(layer.GetLayerDefn());
feature.SetField("NAME", "Beijing");
feature.SetField("POPULATION", 21540000);
Geometry pt = new Geometry(ogr.wkbPoint);
pt.SetPoint_2D(0, 116.4, 39.9);
feature.SetGeometry(pt);
layer.CreateFeature(feature);
feature.delete();
ds.delete();
C#
using OSGeo.OGR;
using OSGeo.OSR;
Ogr.RegisterAll();
Driver driver = Ogr.GetDriverByName("ESRI Shapefile");
DataSource ds = driver.CreateDataSource("output.shp", null);
// 创建图层
SpatialReference srs = new SpatialReference("");
srs.SetWellKnownGeogCS("WGS84");
Layer layer = ds.CreateLayer("output", srs, wkbGeometryType.wkbPoint, null);
// 定义字段
FieldDefn nameField = new FieldDefn("NAME", FieldType.OFTString);
nameField.SetWidth(64);
layer.CreateField(nameField, 1);
FieldDefn popField = new FieldDefn("POPULATION", FieldType.OFTInteger);
layer.CreateField(popField, 1);
// 创建要素
Feature feature = new Feature(layer.GetLayerDefn());
feature.SetField("NAME", "Beijing");
feature.SetField("POPULATION", 21540000);
Geometry pt = new Geometry(wkbGeometryType.wkbPoint);
pt.SetPoint_2D(0, 116.4, 39.9);
feature.SetGeometry(pt);
layer.CreateFeature(feature);
feature.Dispose();
ds.Dispose();
Coordinate Reference Systems and Coordinate Transformation
C++
#include "ogr_spatialref.h"
// 定义坐标系
OGRSpatialReference srcSRS, dstSRS;
srcSRS.SetWellKnownGeogCS("WGS84"); // EPSG:4326
dstSRS.importFromEPSG(3857); // Web Mercator
// 创建坐标变换
OGRCoordinateTransformation *transform =
OGRCreateCoordinateTransformation(&srcSRS, &dstSRS);
// 变换坐标
double x = 116.4, y = 39.9;
if (transform->Transform(1, &x, &y)) {
// x, y 已变换为 EPSG:3857 坐标
}
OCTDestroyCoordinateTransformation(transform);
Python
from osgeo import osr
# 定义坐标系
src_srs = osr.SpatialReference()
src_srs.SetWellKnownGeogCS("WGS84") # EPSG:4326
dst_srs = osr.SpatialReference()
dst_srs.ImportFromEPSG(3857) # Web Mercator
# 创建坐标变换
transform = osr.CoordinateTransformation(src_srs, dst_srs)
# 变换坐标
x, y, z = transform.TransformPoint(116.4, 39.9)
Java
import org.gdal.osr.SpatialReference;
import org.gdal.osr.CoordinateTransformation;
import org.gdal.osr.osr;
// 定义坐标系
SpatialReference srcSRS = new SpatialReference();
srcSRS.SetWellKnownGeogCS("WGS84"); // EPSG:4326
SpatialReference dstSRS = new SpatialReference();
dstSRS.ImportFromEPSG(3857); // Web Mercator
// 创建坐标变换
CoordinateTransformation transform =
osr.CreateCoordinateTransformation(srcSRS, dstSRS);
// 变换坐标
double[] point = new double[]{116.4, 39.9, 0};
transform.TransformPoint(point);
// point[0], point[1] 已变换为 EPSG:3857 坐标
C#
using OSGeo.OSR;
// 定义坐标系
SpatialReference srcSRS = new SpatialReference("");
srcSRS.SetWellKnownGeogCS("WGS84"); // EPSG:4326
SpatialReference dstSRS = new SpatialReference("");
dstSRS.ImportFromEPSG(3857); // Web Mercator
// 创建坐标变换
CoordinateTransformation transform =
new CoordinateTransformation(srcSRS, dstSRS);
// 变换坐标
double[] point = new double[3] { 116.4, 39.9, 0 };
transform.TransformPoint(point);
// point[0], point[1] 已变换为 EPSG:3857 坐标
Raster Format Conversion and Reprojection
C++
#include "gdal_priv.h"
#include "gdalwarper.h"
GDALAllRegister();
// 格式转换(GeoTIFF → PNG)
GDALDataset *src = (GDALDataset *)GDALOpen("input.tif", GA_ReadOnly);
GDALDriver *pngDriver = GetGDALDriverManager()->GetDriverByName("PNG");
GDALDataset *dst = pngDriver->CreateCopy("output.png", src, FALSE, nullptr, nullptr, nullptr);
GDALClose(dst);
GDALClose(src);
// 重投影(Warp)
GDALDataset *srcDs = (GDALDataset *)GDALOpen("input.tif", GA_ReadOnly);
const char *dstWKT = nullptr;
OGRSpatialReference dstSRS;
dstSRS.importFromEPSG(3857);
dstSRS.exportToWkt(const_cast<char **>(&dstWKT));
GDALWarpOptions *warpOpts = GDALCreateWarpOptions();
warpOpts->hSrcDS = srcDs;
warpOpts->nBandCount = 1;
warpOpts->panSrcBands = (int *)CPLMalloc(sizeof(int));
warpOpts->panSrcBands[0] = 1;
warpOpts->panDstBands = (int *)CPLMalloc(sizeof(int));
warpOpts->panDstBands[0] = 1;
GDALDataset *dstDs = (GDALDataset *)GDALAutoCreateWarpedVRT(
srcDs, nullptr, dstWKT, GRA_Bilinear, 0.0, nullptr);
GDALDriver *tiffDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
GDALDataset *outDs = tiffDriver->CreateCopy("reprojected.tif", dstDs, FALSE, nullptr, nullptr, nullptr);
GDALClose(outDs);
GDALClose(dstDs);
GDALClose(srcDs);
Python
from osgeo import gdal
# 格式转换(GeoTIFF → PNG)
src = gdal.Open("input.tif")
gdal.GetDriverByName("PNG").CreateCopy("output.png", src)
src = None
# 重投影(Warp)
gdal.Warp(
"reprojected.tif",
"input.tif",
dstSRS="EPSG:3857",
resampleAlg="bilinear"
)
# 带更多参数的 Warp
gdal.Warp(
"clipped.tif",
"input.tif",
dstSRS="EPSG:3857",
outputBounds=[12000000, 4000000, 13000000, 5000000],
xRes=100, yRes=100,
resampleAlg="cubic",
creationOptions=["COMPRESS=LZW", "TILED=YES"]
)
Java
import org.gdal.gdal.gdal;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.Driver;
import org.gdal.gdal.WarpOptions;
import java.util.Vector;
gdal.AllRegister();
// 格式转换(GeoTIFF → PNG)
Dataset src = gdal.Open("input.tif");
Driver pngDriver = gdal.GetDriverByName("PNG");
Dataset dst = pngDriver.CreateCopy("output.png", src);
dst.delete();
src.delete();
// 重投影(Warp)
Dataset srcDs = gdal.Open("input.tif");
Vector<String> options = new Vector<>();
options.add("-t_srs");
options.add("EPSG:3857");
options.add("-r");
options.add("bilinear");
WarpOptions warpOpts = new WarpOptions(options);
Dataset[] srcArray = new Dataset[]{srcDs};
Dataset dstDs = gdal.Warp("reprojected.tif", srcArray, warpOpts);
dstDs.delete();
srcDs.delete();
C#
using OSGeo.GDAL;
Gdal.AllRegister();
// 格式转换(GeoTIFF → PNG)
Dataset src = Gdal.Open("input.tif", Access.GA_ReadOnly);
Driver pngDriver = Gdal.GetDriverByName("PNG");
Dataset dst = pngDriver.CreateCopy("output.png", src, 0, null, null, null);
dst.Dispose();
src.Dispose();
// 重投影(Warp)
Dataset srcDs = Gdal.Open("input.tif", Access.GA_ReadOnly);
string[] warpArgs = new string[] {
"-t_srs", "EPSG:3857",
"-r", "bilinear"
};
GDALWarpAppOptions warpOpts = new GDALWarpAppOptions(warpArgs);
Dataset dstDs = Gdal.Warp("reprojected.tif", new Dataset[] { srcDs }, warpOpts, null, null);
dstDs.Dispose();
srcDs.Dispose();
Vector Format Conversion and Spatial Filtering
C++
#include "ogrsf_frmts.h"
GDALAllRegister();
// Shapefile → GeoJSON
GDALDataset *srcDs = (GDALDataset *)GDALOpenEx("input.shp", GDAL_OF_VECTOR, nullptr, nullptr, nullptr);
GDALDriver *jsonDriver = GetGDALDriverManager()->GetDriverByName("GeoJSON");
GDALDataset *dstDs = jsonDriver->Create("output.geojson", 0, 0, 0, GDT_Unknown, nullptr);
OGRLayer *srcLayer = srcDs->GetLayer(0);
// 空间过滤(仅北京周边)
OGREnvelope env;
env.MinX = 116.0; env.MaxX = 117.0;
env.MinY = 39.5; env.MaxY = 40.5;
srcLayer->SetSpatialFilterRect(env.MinX, env.MinY, env.MaxX, env.MaxY);
// 属性过滤
srcLayer->SetAttributeFilter("POPULATION > 1000000");
// 复制图层
OGRLayer *dstLayer = dstDs->CopyLayer(srcLayer, "filtered");
GDALClose(dstDs);
GDALClose(srcDs);
Python
from osgeo import ogr
# Shapefile → GeoJSON
src_ds = ogr.Open("input.shp")
src_layer = src_ds.GetLayer(0)
# 空间过滤
src_layer.SetSpatialFilterRect(116.0, 39.5, 117.0, 40.5)
# 属性过滤
src_layer.SetAttributeFilter("POPULATION > 1000000")
# 输出
json_driver = ogr.GetDriverByName("GeoJSON")
dst_ds = json_driver.CreateDataSource("output.geojson")
dst_ds.CopyLayer(src_layer, "filtered")
dst_ds = None
src_ds = None
# 或使用 gdal.VectorTranslate(更高级)
from osgeo import gdal
gdal.VectorTranslate(
"output.geojson",
"input.shp",
format="GeoJSON",
spatFilter=[116.0, 39.5, 117.0, 40.5],
where="POPULATION > 1000000"
)
Java
import org.gdal.ogr.*;
ogr.RegisterAll();
// Shapefile → GeoJSON
DataSource srcDs = ogr.Open("input.shp", false);
Layer srcLayer = srcDs.GetLayer(0);
// 空间过滤
srcLayer.SetSpatialFilterRect(116.0, 39.5, 117.0, 40.5);
// 属性过滤
srcLayer.SetAttributeFilter("POPULATION > 1000000");
// 输出
Driver jsonDriver = ogr.GetDriverByName("GeoJSON");
DataSource dstDs = jsonDriver.CreateDataSource("output.geojson");
dstDs.CopyLayer(srcLayer, "filtered");
dstDs.delete();
srcDs.delete();
C#
using OSGeo.OGR;
Ogr.RegisterAll();
// Shapefile → GeoJSON
DataSource srcDs = Ogr.Open("input.shp", 0);
Layer srcLayer = srcDs.GetLayerByIndex(0);
// 空间过滤
srcLayer.SetSpatialFilterRect(116.0, 39.5, 117.0, 40.5);
// 属性过滤
srcLayer.SetAttributeFilter("POPULATION > 1000000");
// 输出
Driver jsonDriver = Ogr.GetDriverByName("GeoJSON");
DataSource dstDs = jsonDriver.CreateDataSource("output.geojson", null);
dstDs.CopyLayer(srcLayer, "filtered", null);
dstDs.Dispose();
srcDs.Dispose();
Geometric Operations
C++
#include "ogr_geometry.h"
// 创建几何对象
OGRPoint pt(116.4, 39.9);
OGRLinearRing ring;
ring.addPoint(0, 0);
ring.addPoint(10, 0);
ring.addPoint(10, 10);
ring.addPoint(0, 10);
ring.closeRings();
OGRPolygon polygon;
polygon.addRing(&ring);
// WKT / WKB 互转
char *wkt = nullptr;
polygon.exportToWkt(&wkt);
CPLFree(wkt);
OGRGeometry *geomFromWkt = nullptr;
OGRGeometryFactory::createFromWkt("POINT(116.4 39.9)", nullptr, &geomFromWkt);
OGRGeometryFactory::destroyGeometry(geomFromWkt);
// 空间操作
OGRGeometry *buffer = pt.Buffer(1.0); // 缓冲区
OGRGeometry *inter = polygon.Intersection(&pt); // 交集
OGRGeometry *united = polygon.Union(&pt); // 合并
double dist = polygon.Distance(&pt); // 距离
bool contains = polygon.Contains(&pt); // 包含判断
bool intersects = polygon.Intersects(&pt); // 相交判断
double area = polygon.get_Area(); // 面积
double length = polygon.get_Length(); // 周长
OGRGeometryFactory::destroyGeometry(buffer);
OGRGeometryFactory::destroyGeometry(inter);
OGRGeometryFactory::destroyGeometry(united);
Python
from osgeo import ogr
# 创建几何对象
pt = ogr.Geometry(ogr.wkbPoint)
pt.SetPoint_2D(0, 116.4, 39.9)
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(0, 0)
ring.AddPoint(10, 0)
ring.AddPoint(10, 10)
ring.AddPoint(0, 10)
ring.CloseRings()
polygon = ogr.Geometry(ogr.wkbPolygon)
polygon.AddGeometry(ring)
# WKT / WKB 互转
wkt = polygon.ExportToWkt()
geom_from_wkt = ogr.CreateGeometryFromWkt("POINT(116.4 39.9)")
geom_from_json = ogr.CreateGeometryFromJson('{"type":"Point","coordinates":[116.4,39.9]}')
# 空间操作
buffer = pt.Buffer(1.0) # 缓冲区
inter = polygon.Intersection(pt) # 交集
united = polygon.Union(pt) # 合并
dist = polygon.Distance(pt) # 距离
contains = polygon.Contains(pt) # 包含判断
intersects = polygon.Intersects(pt) # 相交判断
area = polygon.GetArea() # 面积
length = polygon.Length() # 周长
Java
import org.gdal.ogr.Geometry;
import org.gdal.ogr.ogr;
// 创建几何对象
Geometry pt = new Geometry(ogr.wkbPoint);
pt.SetPoint_2D(0, 116.4, 39.9);
Geometry ring = new Geometry(ogr.wkbLinearRing);
ring.AddPoint(0, 0, 0);
ring.AddPoint(10, 0, 0);
ring.AddPoint(10, 10, 0);
ring.AddPoint(0, 10, 0);
ring.CloseRings();
Geometry polygon = new Geometry(ogr.wkbPolygon);
polygon.AddGeometry(ring);
// WKT / WKB 互转
String wkt = polygon.ExportToWkt();
Geometry geomFromWkt = Geometry.CreateFromWkt("POINT(116.4 39.9)");
// 空间操作
Geometry buffer = pt.Buffer(1.0); // 缓冲区
Geometry inter = polygon.Intersection(pt); // 交集
Geometry united = polygon.Union(pt); // 合并
double dist = polygon.Distance(pt); // 距离
boolean contains = polygon.Contains(pt); // 包含判断
boolean intersects = polygon.Intersects(pt); // 相交判断
double area = polygon.GetArea(); // 面积
C#
using OSGeo.OGR;
// 创建几何对象
Geometry pt = new Geometry(wkbGeometryType.wkbPoint);
pt.SetPoint_2D(0, 116.4, 39.9);
Geometry ring = new Geometry(wkbGeometryType.wkbLinearRing);
ring.AddPoint(0, 0, 0);
ring.AddPoint(10, 0, 0);
ring.AddPoint(10, 10, 0);
ring.AddPoint(0, 10, 0);
ring.CloseRings();
Geometry polygon = new Geometry(wkbGeometryType.wkbPolygon);
polygon.AddGeometry(ring);
// WKT / WKB 互转
string wkt;
polygon.ExportToWkt(out wkt);
Geometry geomFromWkt = Geometry.CreateFromWkt("POINT(116.4 39.9)");
// 空间操作
Geometry buffer = pt.Buffer(1.0, 30); // 缓冲区
Geometry inter = polygon.Intersection(pt); // 交集
Geometry united = polygon.Union(pt); // 合并
double dist = polygon.Distance(pt); // 距离
bool contains = polygon.Contains(pt); // 包含判断
bool intersects = polygon.Intersects(pt); // 相交判断
double area = polygon.GetArea(); // 面积
GeoPackage Reading and Writing
GeoPackage is a lightweight geodatabase format of the OGC standard, suitable as a replacement for Shapefile.
C++
#include "ogrsf_frmts.h"
GDALAllRegister();
// 创建 GeoPackage
GDALDriver *driver = GetGDALDriverManager()->GetDriverByName("GPKG");
GDALDataset *ds = driver->Create("data.gpkg", 0, 0, 0, GDT_Unknown, nullptr);
OGRSpatialReference srs;
srs.importFromEPSG(4326);
OGRLayer *layer = ds->CreateLayer("points", &srs, wkbPoint, nullptr);
OGRFieldDefn field("name", OFTString);
layer->CreateField(&field);
OGRFeature *f = OGRFeature::CreateFeature(layer->GetLayerDefn());
f->SetField("name", "TestPoint");
OGRPoint pt(116.4, 39.9);
f->SetGeometry(&pt);
layer->CreateFeature(f);
OGRFeature::DestroyFeature(f);
GDALClose(ds);
// 读取 GeoPackage
GDALDataset *readDs = (GDALDataset *)GDALOpenEx("data.gpkg", GDAL_OF_VECTOR, nullptr, nullptr, nullptr);
OGRLayer *readLayer = readDs->GetLayerByName("points");
readLayer->ResetReading();
OGRFeature *rf;
while ((rf = readLayer->GetNextFeature()) != nullptr) {
printf("%s\n", rf->GetFieldAsString("name"));
OGRFeature::DestroyFeature(rf);
}
GDALClose(readDs);
Python
from osgeo import ogr, osr
# 创建 GeoPackage
driver = ogr.GetDriverByName("GPKG")
ds = driver.CreateDataSource("data.gpkg")
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
layer = ds.CreateLayer("points", srs, ogr.wkbPoint)
layer.CreateField(ogr.FieldDefn("name", ogr.OFTString))
feature = ogr.Feature(layer.GetLayerDefn())
feature.SetField("name", "TestPoint")
pt = ogr.Geometry(ogr.wkbPoint)
pt.SetPoint_2D(0, 116.4, 39.9)
feature.SetGeometry(pt)
layer.CreateFeature(feature)
ds = None
# 读取 GeoPackage
ds = ogr.Open("data.gpkg")
layer = ds.GetLayerByName("points")
for f in layer:
print(f.GetField("name"))
ds = None
Java
import org.gdal.ogr.*;
import org.gdal.osr.SpatialReference;
ogr.RegisterAll();
// 创建 GeoPackage
Driver driver = ogr.GetDriverByName("GPKG");
DataSource ds = driver.CreateDataSource("data.gpkg");
SpatialReference srs = new SpatialReference();
srs.ImportFromEPSG(4326);
Layer layer = ds.CreateLayer("points", srs, ogr.wkbPoint);
layer.CreateField(new FieldDefn("name", ogr.OFTString));
Feature feature = new Feature(layer.GetLayerDefn());
feature.SetField("name", "TestPoint");
Geometry pt = new Geometry(ogr.wkbPoint);
pt.SetPoint_2D(0, 116.4, 39.9);
feature.SetGeometry(pt);
layer.CreateFeature(feature);
ds.delete();
// 读取 GeoPackage
DataSource readDs = ogr.Open("data.gpkg", false);
Layer readLayer = readDs.GetLayerByName("points");
Feature f;
while ((f = readLayer.GetNextFeature()) != null) {
System.out.println(f.GetFieldAsString("name"));
f.delete();
}
readDs.delete();
C#
using OSGeo.OGR;
using OSGeo.OSR;
Ogr.RegisterAll();
// 创建 GeoPackage
Driver driver = Ogr.GetDriverByName("GPKG");
DataSource ds = driver.CreateDataSource("data.gpkg", null);
SpatialReference srs = new SpatialReference("");
srs.ImportFromEPSG(4326);
Layer layer = ds.CreateLayer("points", srs, wkbGeometryType.wkbPoint, null);
layer.CreateField(new FieldDefn("name", FieldType.OFTString), 1);
Feature feature = new Feature(layer.GetLayerDefn());
feature.SetField("name", "TestPoint");
Geometry pt = new Geometry(wkbGeometryType.wkbPoint);
pt.SetPoint_2D(0, 116.4, 39.9);
feature.SetGeometry(pt);
layer.CreateFeature(feature);
ds.Dispose();
// 读取 GeoPackage
DataSource readDs = Ogr.Open("data.gpkg", 0);
Layer readLayer = readDs.GetLayerByName("points");
Feature f;
while ((f = readLayer.GetNextFeature()) != null) {
Console.WriteLine(f.GetFieldAsString("name"));
f.Dispose();
}
readDs.Dispose();
Common Raster Data Formats and Creation Options
| Driver Name | Extension | Description | Common Creation Options |
|---|---|---|---|
GTiff |
.tif |
GeoTIFF, the most commonly used raster format | COMPRESS=LZW/DEFLATE/ZSTD、TILED=YES、BLOCKXSIZE=256 |
COG |
.tif |
Cloud Optimized GeoTIFF | COMPRESS=DEFLATE、OVERVIEW_RESAMPLING=CUBIC |
PNG |
.png |
PNG image | ZLEVEL=6 |
JPEG |
.jpg |
JPEG image | QUALITY=85 |
GPKG |
.gpkg |
GeoPackage raster | TILE_FORMAT=PNG/JPEG/WEBP |
netCDF |
.nc |
NetCDF scientific data format | FORMAT=NC4、COMPRESS=DEFLATE |
HFA |
.img |
Erdas Imagine | — |
VRT |
.vrt |
Virtual dataset (XML reference) | — |
Common Vector Data Formats
| Driver Name | Extension | Description |
|---|---|---|
ESRI Shapefile |
.shp |
ESRI Shapefile, classic vector format |
GeoJSON |
.geojson |
GeoJSON, web-friendly format |
GPKG |
.gpkg |
GeoPackage, OGC standard lightweight database |
PostgreSQL / PostGIS |
— | PostGIS spatial database |
FlatGeobuf |
.fgb |
High-performance streaming binary format |
GML |
.gml |
OGC GML format |
KML |
.kml |
Google Earth format |
CSV |
.csv |
Comma-separated values (with VRT specifying the geometry column) |
SQLite |
.sqlite |
SQLite / SpatiaLite database |
XLSX |
.xlsx |
Excel spreadsheet (read-only) |
Typical Application Scenarios
| Scenario | C++ | Python | Java | C# |
|---|---|---|---|---|
| Read raster metadata | GDALOpen + GetGeoTransform |
gdal.Open + GetGeoTransform |
gdal.Open + GetGeoTransform |
Gdal.Open + GetGeoTransform |
| Raster format conversion | CreateCopy |
gdal.Translate |
gdal.Translate |
Gdal.wrapper_GDALTranslate |
| Raster reprojection | GDALAutoCreateWarpedVRT |
gdal.Warp |
gdal.Warp |
Gdal.Warp |
| Read vector features | GDALOpenEx + GetNextFeature |
ogr.Open + iteration |
ogr.Open + GetNextFeature |
Ogr.Open + GetNextFeature |
| Vector format conversion | CopyLayer / CreateFeature |
gdal.VectorTranslate |
ogr.CopyLayer |
Ogr.CopyLayer |
| Coordinate transformation | OGRCreateCoordinateTransformation |
osr.CoordinateTransformation |
osr.CreateCoordinateTransformation |
new CoordinateTransformation |
| Create buffer | OGRGeometry::Buffer |
geom.Buffer |
geom.Buffer |
geom.Buffer |
| Spatial query | SetSpatialFilterRect |
SetSpatialFilterRect |
SetSpatialFilterRect |
SetSpatialFilterRect |
| SQL query | ExecuteSQL |
ExecuteSQL |
ExecuteSQL |
ExecuteSQL |
| Band math | RasterIO manual calculation |
gdal_calc.py / NumPy |
RasterIO manual calculation |
RasterIO manual calculation |
Common Notes
General Notes
- Driver registration: Before using any GDAL functionality, the registration function must be called. C++ and Python use
GDALAllRegister(), Java usesgdal.AllRegister(), C# usesGdal.AllRegister(). Vector operations also requireOGRRegisterAll()/ogr.RegisterAll()。 - Resource release: C++ uses
GDALClose()/OGRFeature::DestroyFeature(); Python assignment toNonetriggers release; Java calls.delete(); C# calls.Dispose(). Failure to release resources may cause file corruption. - Axis order: GDAL 3.0+ follows the EPSG specification by default (latitude first), and can be forced to longitude first via
OGRSpatialReference::SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER). - Thread safety: GDAL global state is not thread-safe; in multithreaded environments note: each thread uses an independent
GDALDataset; avoid concurrent writes to the same dataset. - Large file handling: For large rasters, use block-based reading and writing (
RasterIOspecifies the window) to avoid reading the entire image into memory at once. - Error handling: Use
CPLGetLastErrorMsg()(C++)、gdal.GetLastErrorMsg()(Python) to obtain detailed error information.
C++-specific notes
- Memory management: Use
CPLFree()to free C strings allocated by GDAL (such asexportToWktWKT returned by exportToWkt). For geometry objects, useOGRGeometryFactory::destroyGeometry()to destroy them. - Compilation and linking: Ensure that you use
gdal-config --cflags --libsor CMakefind_package(GDAL)to correctly configure the compilation parameters.
Python-specific notes
- Exception mode: By default, GDAL Python does not throw exceptions. Enable exception mode:
gdal.UseExceptions()(recommended to call at the beginning of the script). - NumPy integration:
band.ReadAsArray()directly returns NumPy arrays,band.WriteArray(array)directly writes, which is one of Python's greatest conveniences.
Java-specific notes
- Native library loading: You must ensure that
gdalalljni(Linux:libgdalalljni.so,Windows:gdalalljni.dll) is injava.library.path. - Vector parameters: Many methods in the Java bindings use
java.util.Vector<String>to pass option parameters.
C#-specific notes
- Platform runtime: You need to reference the corresponding NuGet runtime package (Linux / Windows / macOS) according to the target platform, otherwise native library loading will fail.
- String encoding: In the C# bindings, string parameters use UTF-8 encoding by default. Pay attention to encoding consistency when handling Chinese paths.
Reference links
- GitHub repository: https://github.com/OSGeo/gdal
- API overview: https://gdal.org/en/stable/api/index.html
- C/C++ API documentation: https://gdal.org/en/stable/api/index.html#c-api
- Python API documentation: https://gdal.org/en/stable/api/python/index.html
- Python bindings documentation: https://gdal.org/en/stable/api/python/python_bindings.html
- Java API documentation: https://gdal.org/en/stable/api/java/index.html
- C# API documentation: https://gdal.org/en/stable/api/csharp/index.html
- SWIG bindings source code: https://github.com/OSGeo/gdal/tree/master/swig
- Official documentation home page: https://gdal.org/en/stable/
- GDAL tutorials: https://gdal.org/en/stable/tutorials/index.html
- Driver format list: https://gdal.org/en/stable/drivers/index.html
- Issue tracking: https://github.com/OSGeo/gdal/issues