[gdal-dev] C# version of gdallocationinfo
Paul Meems
bontepaarden at gmail.com
Wed Feb 22 02:43:41 PST 2017
Hi list,
I need to get the pixel value of my tiff-file.
Using gdallocationinfo.exe I can get the correct value:
gdallocationinfo -wgs84 -valonly 201612021600.tif 5.22543631866552
51.2581472440154
Now I need to do this in my C# code. Using examples I found with Google I
came up with this piece of code, I also looked at the C++ code of
gdallocationinfo
public string GdalLocate(string input, double x, double y, bool inWgs84 =
true)
{
using (var ds = Gdal.Open(input, Access.GA_ReadOnly))
{
if (ds == null) throw new Exception("Can't open GDAL dataset: " +
input);
int col;
int row;
if (inWgs84)
{
var pGT = new double[6];
ds.GetGeoTransform(pGT);
col = (int) Math.Floor((x - pGT[0]) / pGT[1]);
row = (int) Math.Floor((pGT[3] - y) / -pGT[5]);
}
else
{
col = (int)Math.Floor(x);
row = (int)Math.Floor(y);
}
// Check input:
var rows = ds.RasterYSize;
var cols = ds.RasterXSize;
if (col < 0 || row < 0 || col > cols || row > rows)
{
// Location is off this file! No further details to report.
return string.Empty;
}
// Get the first band:
using (var band = ds.GetRasterBand(1))
{
// Creating a C# array to hold the image data
var byteBuffer = new byte[cols * rows];
// Read the raster
var IsThereAnError = band.ReadRaster(row, col, 1, 1,
byteBuffer, 1, 1, 0, 0);
if (IsThereAnError == CPLErr.CE_None) return
byteBuffer[0].ToString();
throw new Exception("Error in reading raster using
GdalLocate.");
}
}
}
The command line call returns 29.
My method using the same input file and coordinates returns 1.
So I must be missing something!
Thanks in advanced for any help you can provide.
Paul
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/gdal-dev/attachments/20170222/0da77f86/attachment.html>
More information about the gdal-dev
mailing list