Skip to content

Commit

Permalink
support embedding GDALMetadata with tiffset #317
Browse files Browse the repository at this point in the history
  • Loading branch information
bossie committed Oct 25, 2024
1 parent 2a25a26 commit 4f1ede1
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -922,4 +922,24 @@ package object geotiff {
result.collect()
print("test done")
}

// TODO: favor dedicated XML type over String?
def embedGdalMetadata(gdalMetadataXml: String, geotiffPath: Path): Unit = {
import scala.sys.process._
import java.nio.charset._

val outputBuffer = new StringBuilder
val processLogger = ProcessLogger(line => outputBuffer appendAll line)

val tempFile = Files.createTempFile("GDALMetadata_", ".xml.tmp")
try {
Files.write(tempFile, s"$gdalMetadataXml\n".getBytes(StandardCharsets.US_ASCII))

val args = Seq("tiffset", "-sf", "42112", tempFile.toString, geotiffPath.toString)
val exitCode = args ! processLogger
if (exitCode != 0) {
throw new Exception(s"${args mkString " "} failed; output: $outputBuffer")
}
} finally Files.delete(tempFile)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package org.openeo.geotrellis.geotiff

import geotrellis.raster.io.geotiff.MultibandGeoTiff
import org.junit.jupiter.api.Assertions.{assertEquals, assertThrows, assertTrue}
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir

import java.nio.file.{Files, Path, Paths}

class PackageTest {

@Test
def testEmbedGdalMetadata(@TempDir tempDir: Path): Unit = {
val geotiffCopy = tempDir.resolve("copy.tif")
Files.copy(getClass.getResourceAsStream("/org/openeo/geotrellis/cgls_ndvi300.tif"), geotiffCopy)

assertTrue(processingSoftware(geotiffCopy).isEmpty)

val gdalMetadataXml =
<GDALMetadata>
<Item name="PROCESSING_SOFTWARE">0.45.0a1</Item>
<Item name="DESCRIPTION" sample="0">CO</Item>
</GDALMetadata>

embedGdalMetadata(gdalMetadataXml.toString(), geotiffCopy)

assertEquals(Some("0.45.0a1"), processingSoftware(geotiffCopy))
}

@Test
def testEmbedGdalMetadataFails(): Unit = {
val e = assertThrows(classOf[Exception], () =>
embedGdalMetadata(gdalMetadataXml = "", geotiffPath = Paths.get("doesnotexist.tif")))

assertTrue(e.getMessage contains "doesnotexist.tif: No such file or directory")
}

private def processingSoftware(geotiff: Path): Option[String] =
MultibandGeoTiff(geotiff.toString).tags.headTags.get("PROCESSING_SOFTWARE")
}

0 comments on commit 4f1ede1

Please sign in to comment.