0

I am trying to get my head around the GDAL C API. I have some arrays which contains int, float or double values and when I try to dump them to a tiff file using GDALRasterIO I get raster with vertical band alternating with 0 values (uninitialised values I suspect...

Here is a minimal example:

#include "gdal.h"

void create_new_tiff(char * DstFilename, int nx, int ny);

int main()
{
char  filename[10] = "test.tif";
int nx, ny;

nx = 600;
ny = 500;

create_new_tiff(filename, nx, ny);

return 0;
}

And the create_new_tiff function:

void create_new_tiff(char * DstFilename, int nx, int ny)
{

const char *pszFormat = "GTiff";
int test[nx*ny];
GDALDatasetH hDstDS;
GDALRasterBandH hBand;
char **papszOptions = NULL;

GDALAllRegister();
GDALDriverH hDriver = GDALGetDriverByName( pszFormat );

hDstDS = GDALCreate( hDriver, DstFilename, nx, ny, 1, GDT_Int16, papszOptions);
hBand = GDALGetRasterBand( hDstDS, 1 );

for(int i=0; i<nx*ny; i++) test[i] = 4;

CPLErr Err = GDALRasterIO( hBand, GF_Write, 0, 0, nx, ny, test, nx, ny, GDT_Int16, 0, 0);
GDALClose( hDstDS );
}

Looks like I am confusing data type but can't figure out what is wrong...

Thanks

PS: Here is what the raster looks like in QGis:

enter image description here

rbeucher
  • 143
  • 8
  • 1
    int is GDT_Int32. Change your array to short, or your data type to GDT_Int32. –  Jun 22 '16 at 16:22
  • Isn't “int" 16 bits ? – rbeucher Jun 22 '16 at 20:17
  • OK I thought int was 2 bytes by default but it actually depends on the implementation. See https://stackoverflow.com/questions/3946268/is-int-by-default-long-int-in-c – rbeucher Jun 22 '16 at 20:24
  • Actually it does not work. I have a raster with NaN values only... – rbeucher Jun 23 '16 at 06:21
  • That maybe QGIS just misinterpreting the values. Fiddle with the style, and load the 'actual' min/max from the raster. –  Jun 23 '16 at 15:08

1 Answers1

1

The mistake comes from the fact that I was assuming that "int" was actually 2 bytes by default which is wrong. The size of int depends on the implementation. See is int by default long int in C?

See kyle comment

rbeucher
  • 143
  • 8