[GIS] gdal_translate – raw to png

gdal-translate

I have a raw binary file containing color (RGB, 1byte per channel) with band interleaved by pixel (BIP) layout that I'd like to translate to a PNG. I could probably use some other non-GIS specific tool for this (recommendations welcome), but I'd prefer to use gdal_translate since it's already in my pipeline and has done a good job of translating other formats for me.

Is it possible to use raw files as input to gdal_translate?

Best Answer

You have an 8 bit 3 band binary file, interleaved by pixel. Assuming you don't already have a header file that GDAL understands and you know the number of columns and rows, you can create (in code or by hand) a VRT file that describes the layout of the binary file so that GDAL can read it. Write something like the following to a file (can be called anything you like)

<VRTDataset rasterXSize="400" rasterYSize="300">
  <VRTRasterBand dataType="Byte" band="1" subClass="VRTRawRasterBand">
    <SourceFilename relativetoVRT="0">/path/to/file.raw</SourceFilename>
    <ImageOffset>0</ImageOffset>
    <PixelOffset>3</PixelOffset>
    <LineOffset>1200</LineOffset>
  </VRTRasterBand>
  <VRTRasterBand dataType="Byte" band="2" subClass="VRTRawRasterBand">
    <SourceFilename relativetoVRT="0">/path/to/file.raw</SourceFilename>
    <ImageOffset>1</ImageOffset>
    <PixelOffset>3</PixelOffset>
    <LineOffset>1200</LineOffset>
  </VRTRasterBand>
  <VRTRasterBand dataType="Byte" band="3" subClass="VRTRawRasterBand">
    <SourceFilename relativetoVRT="0">/path/to/file.raw</SourceFilename>
    <ImageOffset>0</ImageOffset>
    <PixelOffset>3</PixelOffset>
    <LineOffset>1200</LineOffset>
  </VRTRasterBand>
</VRTDataset>

From the GDAL VRT tutorial:

  • SourceFilename: The name of the raw file containing the data for this band. The relativeToVRT attribute can be used to indicate if the SourceFilename is relative to the .vrt file (1) or not (0).

  • ImageOffset: The offset in bytes to the beginning of the first pixel of data of this image band. Defaults to zero.

  • PixelOffset: The offset in bytes from the beginning of one pixel and the next on the same line. In packed single band data this will be the size of the dataType in bytes.

  • LineOffset: The offset in bytes from the beginning of one scanline of data and the next scanline of data. In packed single band data this will be PixelOffset * rasterXSize.

So the only things you'll need to change in the example are rasterXSize, rasterYSize, SourceFilename and LineOffset. LineOffset will be 3 x rasterXSize.

You can then use gdal_translate to convert the VRT to PNG:

gdal_translate {appropriate options if required} /path/to/file.vrt /path/to/file.png

Related Question