GDAL Translate – Convert TIFF to PNG with Added Alpha Channel

cloud-optimized-geotiffgdalgdal-translate

I am using gdal_translate to create a Cloud Optimized GeoTIFF:

  gdal_translate ${lvl2_cub} ${tifname} \
                          -co COMPRESS=LZW -co TILED=YES -b ${gdalidx} -co BIGTIFF=YES \
                          -strict -r bilinear -co BLOCKXSIZE=512 -co BLOCKYSIZE=512
  gdaladdo -r lanczos --config COMPRESS_OVERVIEW LZW \
                          ${tifname} 2 4 8 16 32 64
  gdal_translate ${tifname} ${cogname} -co COMPRESS=LZW -co TILED=YES \
                    -co PREDICTOR=2 -co COPY_SRC_OVERVIEWS=YES \
                    -co BLOCKXSIZE=512 -co BLOCKYSIZE=512 --config GDAL_TIFF_OVR_BLOCKSIZE 512

The resulting COG is a 32-bit file. I am then attempting to create an 8-bit thumbnail (JPG or PNG are both workable) where the no data value is mapped to zero and is transparent. To do this, I am pretty sure that I need to get an alpha channel added to the PNG, but the driver does not have a -co ALPHA=YES like the GeoTIFF driver.

Here is my attempt at a gdal_translate call:

gdal_translate -ot Byte -scale $minval $ maxval 1 255 -outsize 300 0 -a_nodata 0 "${cogname}" "${outsubdir}/${name_wo_extension}.png"

How can one add an alpha channel to a PNG using gdal_translate when the input data are single band, grayscale COGs?

Best Answer

By the driver documentation https://gdal.org/drivers/raster/png.html grayscale with alpha is not supported even the PNG format does support it http://libpng.org/pub/png/spec/1.2/PNG-DataRep.html

I checked also that the GDAL autotests for PNG have some tests for RGBA but not any for grayscale+alpha. However, setting a nodata value should be enough, nodata and alpha are alternative ways for defining transparency/nodata.

Related Question