Clipping TIF Files with GDAL
8/12/24Less than 1 minute
Clipping TIF Files with GDAL
- Create GPKG
fun createGpkgByStr(dataPath: String, geojson: String): String {
val ctm = System.currentTimeMillis()
val name = "temp$ctm"
val path = dataPath + File.separator + "tmp" + File.separator + "${name}.gpkg"
ogr.RegisterAll()
val ds = ogr.GetDriverByName("GPKG").CreateDataSource(path)
val sr = SpatialReference()
sr.ImportFromEPSG(4326)
val layer = ds.CreateLayer("temp", sr, 3)
val feature = Feature(layer.GetLayerDefn())
val geom = Geometry.CreateFromJson(geojson)
geom.FlattenTo2D()
feature.SetGeometry(geom)
layer.CreateFeature(feature)
// ds.FlushCache()
// ds.SyncToDisk()
// gdal.GDALDestroyDriverManager()
return path
}- Use the created GPKG to clip the TIF
fun clipTif(dataPath: String, srcPath: String, destPath: String, geojson: String) {
gdal.AllRegister()
// val futureTask1 = FutureTask(CreateGpkgCallable(geojson))
// val thread1 = Thread(futureTask1)
// thread1.start()
// val args = futureTask1.get()
val args = createGeojsonByStr(dataPath, geojson)
val vector: Vector<String> = Vector()
val srcDs: Dataset = gdal.Open(srcPath, gdalconstConstants.GA_ReadOnly)
"-overwrite -t_srs EPSG:4326 -of GTiff -cutline $args -cl temp -crop_to_cutline"
.split(" ").forEach { vector.add(it) }
gdal.Warp(destPath, arrayOf(srcDs), WarpOptions(vector))
val f = File(args)
if (f.exists()) f.delete()
}AI Translation | AI 翻译
This article was translated from Chinese to English by AI. If there are any inaccuracies, please refer to the original Chinese version.
本文由 AI 辅助从中文翻译为英文。如遇不准确之处,请以中文原版为准。
