Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a geotiff from an existing bitmap in C# with gdal

I have to use gdal in a c# project. The thing I have to do is to "convert" a simple bitmap into a GeoTiff. I read some documentation on the gdal website but I didn't succeed to make it work perfectly. In fact my bitmap is successfuly exported to a geotiff, but if I open the geotiff with a GIS software (for instance QuantumGIS) the GeoTiff is inverted on the y-axis :

enter image description here :

Whereas the original bitmap look like this :

enter image description here

Here is what I've done :

First I write a temp file to the disk (that is the bitmap), I create a dataset containing the bitmap thanks to gdal function (Gdal.Open(path)), and I create a new dataset (with the GTiff driver) using the bitmap dataset , I set the geo transformation and I write the geotiff to the disk :

  String wktProj = null;
  String tmpPath = @"C:\tmp.bmp";
  Bitmap tmpBitmap = bmp.Clone(new Rectangle(0, 0, bmp.Width, bmp.Height), pixFormat);
  tmpBitmap.Save(tmpPath, ImageFormat.Bmp);

  String[] options = null;
  Gdal.AllRegister();
  OSGeo.GDAL.Driver srcDrv = Gdal.GetDriverByName("GTiff");
  Dataset srcDs = Gdal.Open(tmpPath, Access.GA_ReadOnly);
  Dataset dstDs = srcDrv.CreateCopy(path, srcDs, 0, options, null, null);

  //Set the map projection
  Osr.GetWellKnownGeogCSAsWKT("WGS84", out wktProj);
  dstDs.SetProjection(wktProj);

  //Set the map georeferencing
  double mapWidth = Math.Abs(latLongMap.listBounds.topRight.x - latLongMap.listBounds.bottomLeft.x);
  double mapHeight = Math.Abs(latLongMap.listBounds.topRight.y - latLongMap.listBounds.bottomLeft.y);
  double[] geoTransfo = new double[] { -5.14, mapWidth / bmp.Width, 0, 48.75, 0, mapHeight / bmp.Height };
  dstDs.SetGeoTransform(geoTransfo);

  dstDs.FlushCache();
  dstDs.Dispose();
  srcDs.Dispose();
  srcDrv.Dispose();
  tmpBitmap.Dispose();

  File.Delete(tmpPath);

Any idea on what I'm doing wrong ?

Edit I don't know if it is important but the pixels bitmap are 8bppIndexed.

like image 590
Ashbay Avatar asked Oct 31 '12 13:10

Ashbay


1 Answers

To solve the problem I replace this line :

double[] geoTransfo = new double[] { -5.14, mapWidth / bmp.Width, 0, 48.75, 0, mapHeight / bmp.Height };

By this one :

double[] geoTransfo = new double[] { -5.14, mapWidth / bmp.Width, 0, 48.75, 0, (mapHeight / bmp.Height)*(-1) };

It looks the pixel size (height) has to be negative.

like image 161
Ashbay Avatar answered Sep 19 '22 17:09

Ashbay