I came across a scenario where I had to convert geoTiff Files in bulk to png or jpg images to be consumed by code and displayed on the website. So I decided to write Powershell script to do this. This article explains the code to convert tiff files to png/jpg.
GeoTiff
A GeoTIFF(.tif/.tiff) file extension contains geographic metadata that describes the actual location in space that each pixel in an image represents. In creating a GeoTIFF file, spatial information is included in the .tif file as embedded tags, which can include raster image metadata such as,
- horizontal and vertical datums
- spatial extent, i.e. the area that the dataset covers
- the coordinate reference system (CRS) used to store the data
- spatial resolution, measured in the number of independent pixel values per unit length
- the number of layers in the .tif file
- ellipsoids and geoids - estimated models of the Earth’s shape
- mathematical rules for map projection to transform data for a three-dimensional space into a two-dimensional display
Jpg/Png
These are usual photo formats which can be used readily in standard apps to display the image
Powershell
PowerShell runs on Windows, Linux, and macOS. PowerShell is a cross-platform task automation solution made up of a command-line shell, a scripting language, and a configuration management framework.
function ConvertImage {
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true)]
[string] $path = 'c:\tifffiles\sample01_Images', #path to files[Parameter(Mandatory = $true)]
[string] $jpgOrpng = 'png')
if (Test - Path $path) {
$files = Get - ChildItem - Path $path - Filter * .tif - Recurse - ErrorAction SilentlyContinue - Force | select FullName;
echo $files;
#Load required assemblies and get object reference[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out - Null
foreach($file in $files) {
$convertfile = new - object System.Drawing.Bitmap($file.Fullname)
$newfilname = ($file.Fullname - replace '([^.]).tif', '$1') + "." + $jpgOrpng
$convertfile.Save($newfilname, $jpgOrpng)
$file.Fullname
}
} else {
Write - Host "Path not found."
}
}
Usage
1. Convert tiff/geotiff to png
. ./convert.ps1
ConvertImage -path 'E:\projects\files' -jpgOrpng 'png'
2. Convert tiff/geotiff to jpg
. ./convert.ps1
ConvertImage -path 'E:\projects\files' -jpgOrpng 'jpg'
Note
To run and develop the script on a local machine you need to set the execution policy to unrestricted.
Set-ExecutionPolicy Unrestricted
Complete code is available here - https://github.com/santoshkaranam/convertTif2PngOrJpg
This code uses System.Windows.Forms to convert the image from tiff to png/jpg.
This is a sample code to convert tiff(.tif or .tiff) files to png/jpg.
References
- https://www.heavy.ai/technical-glossary/geotiff