public override IRasterDataProvider Create(string fileName, int xSize, int ySize, int bandCount, enumDataType dataType, params object[] options) { string[] driverOptions; string drvName = GetDriverName(options, out driverOptions); if (string.IsNullOrEmpty(drvName)) { throw new ArgumentException("没有指定或者指定了错误的驱动名称!"); } if (driverOptions == null) { driverOptions = new string[] { "INTERLEAVE=BSQ" } } ; using (Driver drv = Gdal.GetDriverByName(drvName)) { double[] geoTransform; string wktPrj; GetGDALOptions(driverOptions, out geoTransform, out wktPrj); using (Dataset ds = drv.Create(fileName, xSize, ySize, bandCount, GetDataType(dataType), driverOptions)) { if (geoTransform != null && geoTransform.Length == 6) { ds.SetGeoTransform(geoTransform); } if (!string.IsNullOrWhiteSpace(wktPrj)) { ds.SetProjection(wktPrj); } //FillZero(ds,dataType); } } return(GeoDataDriver.Open(fileName, enumDataProviderAccess.Update, null) as IRasterDataProvider); }
private void Functions_CollectionChanging(object sender, NotifyCollectionChangingEventArgs e) { if (!AutoOpen()) { return; } if ((e.Action == NotifyCollectionChangeAction.Add || e.Action == NotifyCollectionChangeAction.Replace) && e.Item is IRegularGridCoverage) { var grid = (IRegularGridCoverage)e.Item; var driverName = GdalHelper.GetDriverName(path); RegisterGdal(); using (var gdalDriver = Gdal.GetDriverByName(driverName)) { var gdalType = GdalHelper.GetGdalDataType(gdalDriver, grid.Components[0].ValueType); var gdalvariableValue = GdalHelper.GetVariableForDataType(gdalType);// TODO: strange logic, use supported GDAL types here (as .NET types) instead var type = gdalvariableValue.ValueType; if (type != grid.Components[0].ValueType) { throw new InvalidOperationException(string.Format("Value type {0} is not supported by GDAL driver", grid.Components[0].ValueType)); } } } }
private static Driver GetTargetDatasetDriver(string path) { var driverName = GdalHelper.GetDriverName(path); RegisterGdal(); return(Gdal.GetDriverByName(driverName)); }
public void AllDriversAvailable() { // list of common drivers var drivers = new[] { "hdf4", "hdf5", "gtiff", "aaigrid", "adrg", "airsar", "arg", "blx", "bmp", "bsb", "cals", "ceos", "coasp", "cosar", "ctg", "dimap", "dted", "e00grid", "elas", "ers", "fit", "gff", "gxf", "hf2", "idrisi", "ignfheightasciigrid", "ilwis", "ingr", "iris", "jaxapalsar", "jdem", "kmlsuperoverlay", "l1b", "leveller", "map", "mrf", "msgn", "ngsgeoid", "nitf", "pds", "prf", "r", "rmf", "rs2", "safe", "saga", "sdts", "sentinel2", "sgi", "sigdem", "srtmhgt", "terragen", "til", "tsx", "usgsdem", "xpm", "xyz", "zmap", "rik", "ozi", "grib", "rasterlite", "mbtiles", "pdf", "aeronavfaa", "arcgen", "bna", "cad", "csv", "dgn", "dxf", "edigeo", "geoconcept", "georss", "gml", "gpsbabel", "gpx", "htf", "jml", "mvt", "openair", "openfilegdb", "pgdump", "rec", "s57", "segukooa", "segy", "selafin", "ESRI Shapefile", "sua", "svg", "sxf", "tiger", "vdv", "wasp", "xplane", "idrisi", "pds", "sdts", "gpkg", "vfk", "osm" }; foreach (var driver in drivers) { var driverByName = Gdal.GetDriverByName(driver); _outputHelper.WriteLine( driverByName != default ? $"{driver} loaded successfully" : $"Failed to load {driver}"); Assert.NotNull(driverByName); } }
private void SetDriver(string path) { using (var driver = gdalDataset.GetDriver()) { if (!GdalHelper.IsCreateSupported(driver)) { log.WarnFormat("Datasource is readonly: {0}", path); return; } //cannot directly create dataset. check if dataset can be created by copying from another set if (GdalHelper.IsCreateCopySupported(driver)) { //TODO: fix this criteria if (GetDatasetSize() < 1000000) { log.Debug("Using in-memory driver to facilitate writing to datasource"); //log.WarnFormat("Using in memory-driver with large dataset can yield unexpected results."); using (var gdalDriver = Gdal.GetDriverByName("MEM")) { var oldGdalDataSet = gdalDataset; gdalDataset = gdalDriver.CreateCopy(path, gdalDataset, 0, new string[] { }, null, null); oldGdalDataSet.Dispose(); } } } } }
private static Dataset CreateTiff(string Filename, double[] GeoTransform, string Projection, PixelLims shape, bool CreateCompressed, float?NDV, int?BlockSize) { var creationOpts = new List <string>(); if (CreateCompressed) { creationOpts = new List <string>() { "COMPRESS=DEFLATE", "ZLEVEL=9", "TILED=YES", "SPARSE_OK=FALSE", "BIGTIFF=YES", "NUM_THREADS=ALL_CPUS" }; } if (BlockSize.HasValue) { creationOpts.Add("BLOCKXSIZE=" + BlockSize.Value.ToString()); creationOpts.Add("BLOCKYSIZE=" + BlockSize.Value.ToString()); } var drv = Gdal.GetDriverByName("GTiff"); var shapeX = shape.EastPixelCoord - shape.WestPixelCoord; var shapeY = shape.SouthPixelCoord - shape.NorthPixelCoord; var ds = drv.Create(Filename, (int)shapeX, (int)shapeY, 1, DataType.GDT_Float32, creationOpts.ToArray()); ds.SetGeoTransform(GeoTransform); ds.SetProjection(Projection); var band = ds.GetRasterBand(1); if (NDV.HasValue) { band.SetNoDataValue(NDV.Value); } return(ds); }
public static string SaveDataInFile(string filename, IEnumerable data, int width, int height, DataType dataType, double[] argin = null, string shapeSrs = null) { OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("GTiff"); using (Dataset outputDataset = outputDriver.Create(filename, width, height, 1, dataType, null)) { if (argin != null) { outputDataset.SetGeoTransform(argin); } Band outputband = outputDataset.GetRasterBand(1); switch (dataType) { case DataType.GDT_UInt16: outputband.WriteRaster(0, 0, width, height, (short[])data, width, height, 0, 0); break; case DataType.GDT_Byte: outputband.WriteRaster(0, 0, width, height, (byte[])data, width, height, 0, 0); break; } if (!string.IsNullOrEmpty(shapeSrs)) { outputDataset.SetProjection(shapeSrs); } outputDataset.FlushCache(); outputband.FlushCache(); } return(filename); }
public void GetSupportedGDalDataType() { Driver gdalDriverForBilFile = Gdal.GetDriverByName("EHdr"); var type = GdalHelper.GetGdalDataType(gdalDriverForBilFile, typeof(double)); Assert.AreEqual(DataType.GDT_Float32, type); }
public static bool WriteWholeTiff(string Filename, float[] Data, double[] GeoTransform, string Projection, PixelLims shape, bool CreateCompressed, float?NDV) { // we will create a tiff with tiles (blocks) but let the size of them be specified automatically var ds = CreateTiff(Filename, GeoTransform, Projection, shape, CreateCompressed, NDV, null); var creationOpts = new string[0]; if (CreateCompressed) { creationOpts = new string[] { "COMPRESS=DEFLATE", "ZLEVEL=9", "TILED=YES", "SPARSE_OK=FALSE", "BIGTIFF=YES" }; } var drv = Gdal.GetDriverByName("GTiff"); var shapeX = shape.EastPixelCoord - shape.WestPixelCoord; var shapeY = shape.SouthPixelCoord - shape.NorthPixelCoord; if (shapeX * shapeY != Data.Length) { return(false); } var band = ds.GetRasterBand(1); band.WriteRaster(0, 0, (int)shapeX, (int)shapeY, Data, (int)shapeX, (int)shapeY, 0, 0); band.FlushCache(); ds.FlushCache(); return(true); }
private Dataset CreatePngDataset(int idOverview, int xoff, int yoff, int tileSize, bool hasAlpha) { string[] aryOption = { "" }; OSGeo.GDAL.Driver drv = Gdal.GetDriverByName("MEM"); int nBand = hasAlpha ? _ds.RasterCount + 1 : _ds.RasterCount; Dataset dsReturn = drv.Create("filememory", tileSize, tileSize, nBand, _ds.GetRasterBand(1).DataType, aryOption); dsReturn.SetProjection(_ds.GetProjection()); double[] _gt = new double[6]; _ds.GetGeoTransform(_gt); if (idOverview != -1) { _gt[1] *= Math.Pow(2, (double)(idOverview + 1)); _gt[5] *= Math.Pow(2, (double)(idOverview + 1)); } _gt[0] += xoff * _gt[1]; // X origin _gt[3] += yoff * _gt[5]; // Y origin dsReturn.SetGeoTransform(_gt); return(dsReturn); }
/// <summary> /// 栅格重建,srPath输入,dsPath输出,1为1=>1, 2为1=>4, 3为1=>9, /// </summary> /// <param name="srPath"></param> /// <param name="dsPath"></param> /// <param name="level"></param> public static void ImgReProject(string srPath, string dsPath, int level = 2) { Console.WriteLine("ReprojectImage开始,lever 2"); double[] geoTran = new double[6]; double[] geoTran2 = new double[6]; //读 OSGeo.GDAL.Gdal.AllRegister(); Dataset ds = Gdal.Open(srPath, Access.GA_ReadOnly); ds.GetGeoTransform(geoTran); geoTran2 = geoTran; geoTran2[1] = geoTran[1] / level; geoTran2[5] = geoTran[5] / level; //建 OSGeo.GDAL.Driver gdalDriver = Gdal.GetDriverByName("HFA"); Dataset ods = gdalDriver.Create(dsPath, ds.RasterXSize * level, ds.RasterYSize * level, 1, DataType.GDT_Float32, null); ods.SetProjection(ds.GetProjection()); ods.SetGeoTransform(geoTran2); ods.GetRasterBand(1).SetNoDataValue(-999999); //写 Gdal.ReprojectImage(ds, ods, null, null, ResampleAlg.GRA_NearestNeighbour, 0, 0.02, null, null); ds.Dispose(); ods.Dispose(); Console.WriteLine("ReprojectImage完成"); }
private void SetDriver(string path) { using (var driver = gdalDataset.GetDriver()) { if (GdalHelper.IsCreateCopyOnlySupported(driver)) { log.WarnFormat("Datasource is readonly: {0}", path); return; } //cannot directly create dataset. check if dataset can be created by copying from another set if (GdalHelper.IsCreateCopySupported(driver)) { if (gdalDataset.RasterCount > 1000) { log.WarnFormat("Using in memory-driver with large dataset can yield unexpected results."); } log.WarnFormat("Using in memory-driver with large dataset can yield unexpected results."); } else { using (var gdalDriver = Gdal.GetDriverByName("MEM")) { var oldGdalDataSet = gdalDataset; gdalDataset = gdalDriver.CreateCopy(path, gdalDataset, 0, new string[] { }, null, null); oldGdalDataSet.Dispose(); } } } }
private Dataset getDataset(string outFileName, string refFile) { Dataset refDs = Gdal.Open(refFile, Access.GA_ReadOnly); Band band = refDs.GetRasterBand(1); int bXSize, bYSize; int w, h; w = refDs.RasterXSize; h = refDs.RasterYSize; bXSize = w; bYSize = 1; Driver drv = Gdal.GetDriverByName("GTiff"); string[] options = new string[] { "BLOCKXSIZE=" + bXSize, "BLOCKYSIZE=" + bYSize }; Dataset ds = drv.Create(outFileName, w, h, 1, DataType.GDT_Int16, options); double[] argout = new double[4]; refDs.GetGeoTransform(argout); ds.SetGeoTransform(argout); ds.SetGCPs(refDs.GetGCPs(), ""); return(ds); }
public new TerrainTile GetTerrainTile(double latitude, double longitude, double samplesPerDegree) { //Get Empty Terrain Tile TerrainTile tt = base.GetTerrainTile(latitude, longitude, samplesPerDegree); //Populate target .bil file with data from DataSet string cachefile = tt.TerrainTileFilePath; //work out lines and pixels to extract from VRT int startpixel = (int)Math.Floor((tt.West - m_transform[0]) / m_transform[1]); int endpixel = (int)Math.Ceiling((tt.East - m_transform[0]) / m_transform[1]); int startline = (int)Math.Floor((tt.North - m_transform[3]) / m_transform[5]); int endline = (int)Math.Ceiling((tt.South - m_transform[3]) / m_transform[5]); int xsize = endpixel - startpixel; int ysize = endline - startline; //Allow partial raster access for beyond edge cases int realstartpixel = Math.Max(0, startpixel); int realstartline = Math.Max(0, startline); int realendpixel = Math.Min(m_pixels, endpixel); int realendline = Math.Min(m_lines, endline); //Scale target window in case of partial access int realxsize = realendpixel - realstartpixel; int realysize = realendline - realstartline; //Scale buffer window int bufxsize = (int)Math.Round(256.0 * (double)realxsize / (double)xsize); int bufysize = (int)Math.Round(256.0 * (double)realysize / (double)ysize); int xoff = (int)Math.Round(256.0 * (double)(realstartpixel - startpixel) / (double)xsize); int yoff = (int)Math.Round(256.0 * (double)(realstartline - startline) / (double)ysize); int totalbuf = bufxsize * bufysize; //use pixel space and line space instead of separate buffers Int16[] dembuffer = new Int16[totalbuf]; //extract data from vrt try { m_dataset.GetRasterBand(1).ReadRaster(realstartpixel, realstartline, realxsize, realysize, dembuffer, bufxsize, bufysize, 0, 0); } catch { Console.WriteLine("Raster Could not be accessed"); } //write out cache file Driver memdriver = Gdal.GetDriverByName("ENVI"); string[] options = new string[0]; //TODO: Add compression OSGeo.GDAL.Dataset tile_ds = memdriver.Create(cachefile, 256, 256, 1, (DataType)OSGeo.GDAL.GdalConst.GDT_Int16, options); tile_ds.GetRasterBand(1).WriteRaster(xoff, yoff, bufxsize, bufysize, dembuffer, bufxsize, bufysize, 0, 0); tile_ds.Dispose(); return(tt); }
public static bool GetGdalDrivers() { if (_memory_driver != null) { return(true); } GdalConfiguration.ConfigureGdal(); const string gdalFormat = "GTiff"; _memory_driver = Gdal.GetDriverByName("MEM"); _geotif_driver = Gdal.GetDriverByName(gdalFormat); if (!(_memory_driver != null && _geotif_driver != null)) { Console.WriteLine($"Can't load {(_geotif_driver == null ? "GTiff" : "MEM")} driver."); if (_memory_driver != null) { _memory_driver.Dispose(); } if (_geotif_driver != null) { _geotif_driver.Dispose(); } _memory_driver = _geotif_driver = null; return(false); } return(true); }
/// <summary> /// 从影像拿到帖图 /// </summary> /// <param name="inMapPath"></param> /// <param name="saveMapPath"></param> void getDom(string inMapPath, string saveMapPath) { Gdal.AllRegister(); Dataset ds = Gdal.Open(inMapPath, Access.GA_ReadOnly); double[] geoTran = new double[6]; ds.GetGeoTransform(geoTran); Envelope enve = new Envelope(); geom.GetEnvelope(enve); int xoff, yoff, xend, yend, xSize, ySize; Tools.geoToImageSpace(geoTran, enve.MinX, enve.MaxY, out xoff, out yoff); Tools.geoToImageSpace(geoTran, enve.MaxX, enve.MinY, out xend, out yend); xSize = xend - xoff; ySize = yend - yoff; if (File.Exists(saveMapPath)) { File.Delete(saveMapPath); } OSGeo.GDAL.Driver dr = Gdal.GetDriverByName("GTiff"); Dataset outDs = dr.Create(saveMapPath, xSize, ySize, 3, DataType.GDT_UInt16, null); for (int i = 1; i <= ds.RasterCount; i++) { double[] values = new double[xSize * ySize]; ds.GetRasterBand(i).ReadRaster(xoff, yoff, xSize, ySize, values, xSize, ySize, 0, 0); outDs.GetRasterBand(i).WriteRaster(0, 0, xSize, ySize, values, xSize, ySize, 0, 0); } ds.Dispose(); outDs.Dispose(); }
public void AllDriversAvailable(string driver) { var driverByName = Gdal.GetDriverByName(driver); _outputHelper.WriteLine( driverByName != default ? $"{driver} loaded successfully" : $"Failed to load {driver}"); Assert.NotNull(driverByName); }
public void run() { String inFileIce = @"tmp_TEST.tif"; // String inFileIce = @"data\elevation\ETOPO1_Ice_g_geotiff.tif"; String outFileName = @"tmp_FLOW.tif"; Dataset dsIce = Gdal.Open(inFileIce, Access.GA_ReadOnly); Band baIce = dsIce.GetRasterBand(1); Console.WriteLine("Elevation deviation File: " + inFileIce); // Get the width and height of the Dataset - assuming all sizes the same int width = baIce.XSize; int height = baIce.YSize; byte[] flowDirection = new byte[width * height]; short[] flowAccumulation = new short[width * height]; byte[] watershed = new byte[width * height]; short[] elevation = new short[width * height]; baIce.ReadRaster(0, 0, width, height, elevation, width, height, 0, 0); Console.WriteLine("Calculate flow directions"); calculateFlowDirection(width, height, elevation, flowDirection); Console.WriteLine("Calculate watersheds"); calculateWatershed(width, height, flowDirection, watershed); Console.WriteLine("Calculate Fills"); calculateFills(width, height, elevation, flowDirection, watershed); //Console.WriteLine("Calculate flow accumulations"); //calculateFlowAccumulation(width, height, elevation, elevation_deviation, flowDirection, flowAccumulation); if (File.Exists(outFileName)) { File.Delete(outFileName); } Driver drv = Gdal.GetDriverByName("GTiff"); string[] options = new string[] { "BLOCKXSIZE=" + width, "BLOCKYSIZE=" + 1 }; Dataset ds = drv.Create(outFileName, width, height, 1, DataType.GDT_Byte, options); // Dataset ds = drv.Create(outFileName, width, height, 1, DataType.GDT_Int16, options); double[] argout = new double[4]; dsIce.GetGeoTransform(argout); ds.SetGeoTransform(argout); ds.SetGCPs(dsIce.GetGCPs(), ""); Band ba = ds.GetRasterBand(1); ba.WriteRaster(0, 0, width, height, watershed, width, height, 0, 0); ba.FlushCache(); ds.FlushCache(); Console.WriteLine("Done"); }
/// <summary> /// 从影像拿到帖图 /// </summary> /// <param name="inMapPath"></param> /// <param name="saveMapPath"></param> void getDom(string inMapPath, string saveMapPath) { Gdal.AllRegister(); OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); //打开DOM Dataset ds = Gdal.Open(inMapPath, Access.GA_ReadOnly); double[] geoTran = new double[6]; ds.GetGeoTransform(geoTran); //拿边界 Envelope enve = new Envelope(); geom.GetEnvelope(enve); int xoff, yoff, xend, yend, xSize, ySize; Tools.geoToImageSpace(geoTran, enve.MinX, enve.MaxY, out xoff, out yoff); Tools.geoToImageSpace(geoTran, enve.MaxX, enve.MinY, out xend, out yend); xSize = xend - xoff; ySize = yend - yoff; //创建新文件 if (File.Exists(saveMapPath)) { File.Delete(saveMapPath); } OSGeo.GDAL.Driver dr = Gdal.GetDriverByName("GTIFF"); Dataset outDs = dr.Create(saveMapPath, xSize, ySize, 3, DataType.GDT_Byte, null);// --------------------for test geoTran[0] = enve.MinX; geoTran[3] = enve.MaxY; outDs.SetGeoTransform(geoTran); for (int i = 1; i <= ds.RasterCount; i++) { int[] values = new int[xSize * ySize]; ds.GetRasterBand(i).ReadRaster(xoff, yoff, xSize, ySize, values, xSize, ySize, 0, 0); Band band = outDs.GetRasterBand(i); band.WriteRaster(0, 0, xSize, ySize, values, xSize, ySize, 0, 0); band.FlushCache(); outDs.FlushCache(); } for (int b = 1; b < 4; b++) { double min, max, mean, std; Band oriBand = ds.GetRasterBand(b); Band band = outDs.GetRasterBand(b); //P1 是否接受小误差 --------------------for test oriBand.ComputeStatistics(true, out min, out max, out mean, out std, null, ""); band.SetStatistics(min, max, mean, std); band.FlushCache(); } outDs.Dispose(); ds.Dispose(); }
public void ReadAndWriteImage(string imagePath, string outImagePath) { using (Dataset image = Gdal.Open(imagePath, Access.GA_ReadOnly)) { Band redBand = GetBand(image, ColorInterp.GCI_RedBand); Band greenBand = GetBand(image, ColorInterp.GCI_GreenBand); Band blueBand = GetBand(image, ColorInterp.GCI_BlueBand); Band alphaBand = GetBand(image, ColorInterp.GCI_AlphaBand); if (redBand == null || greenBand == null || blueBand == null || alphaBand == null) { throw new NullReferenceException("One or more bands are not available."); } int width = redBand.XSize; int height = redBand.YSize; using (Dataset outImage = Gdal.GetDriverByName("GTiff").Create(outImagePath, width, height, 4, redBand.DataType, null)) { // copia a projeção e informações geográficas da imagem double[] geoTransformerData = new double[6]; image.GetGeoTransform(geoTransformerData); outImage.SetGeoTransform(geoTransformerData); outImage.SetProjection(image.GetProjection()); Band outRedBand = outImage.GetRasterBand(1); Band outGreenBand = outImage.GetRasterBand(2); Band outBlueBand = outImage.GetRasterBand(3); Band outAlphaBand = outImage.GetRasterBand(4); for (int h = 0; h < height; h++) { int[] red = new int[width]; int[] green = new int[width]; int[] blue = new int[width]; int[] alpha = new int[width]; // copia cada linha da matriz da imagem para os vetores definidos acima redBand.ReadRaster(0, h, width, 1, red, width, 1, 0, 0); greenBand.ReadRaster(0, h, width, 1, green, width, 1, 0, 0); blueBand.ReadRaster(0, h, width, 1, blue, width, 1, 0, 0); alphaBand.ReadRaster(0, h, width, 1, alpha, width, 1, 0, 0); for (int w = 0; w < width; w++) { red[w] = red[w] + 1; // algum processo com cada pixel green[w] = green[w] + 1; blue[w] = blue[w] + 1; alpha[w] = alpha[w] + 1; } // escrever imagem outRedBand.WriteRaster(0, h, width, 1, red, width, 1, 0, 0); outGreenBand.WriteRaster(0, h, width, 1, green, width, 1, 0, 0); outBlueBand.WriteRaster(0, h, width, 1, blue, width, 1, 0, 0); outAlphaBand.WriteRaster(0, h, width, 1, alpha, width, 1, 0, 0); } outImage.FlushCache(); } } }
private void _DatasetPng2File(Dataset ds, string sFileName) { OSGeo.GDAL.Driver drv = Gdal.GetDriverByName("PNG"); string[] aryOption = { "" }; Dataset dsOut = drv.CreateCopy(sFileName, ds, 0, aryOption, null, null); dsOut.FlushCache(); dsOut.Dispose(); }
private static void StartClippingProcess(Layer layer, string rasterName, double rasterCellSize, out Dataset outAlignedRaster) { DriverUtils.RegisterGdalOgrDrivers(); //Extrac srs from input feature string inputShapeSrs; SpatialReference spatialRefrence = layer.GetSpatialRef(); spatialRefrence.ExportToWkt(out inputShapeSrs); Envelope envelope = new Envelope(); layer.GetExtent(envelope, 0); //Compute the out raster cell resolutions int x_res = Convert.ToInt32((envelope.MaxX - envelope.MinX) / rasterCellSize); int y_res = Convert.ToInt32((envelope.MaxY - envelope.MinY) / rasterCellSize); Dataset oldRasterDataset = Gdal.Open(rasterName, Access.GA_ReadOnly); //No of bands in older dataset int rasterBands = oldRasterDataset.RasterCount; //Create new tiff in disk string tempRaster = "tempValueRaster.tif"; if (File.Exists(tempRaster)) { File.Delete(tempRaster); } OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("GTiff"); outAlignedRaster = outputDriver.Create(tempRaster, x_res, y_res, rasterBands, DataType.GDT_Float32, null); //Geotransform double[] argin = new double[] { envelope.MinX, rasterCellSize, 0, envelope.MaxY, 0, -rasterCellSize }; outAlignedRaster.SetGeoTransform(argin); //Set no data for (int rasBand = 1; rasBand <= rasterBands; rasBand++) { Band band = outAlignedRaster.GetRasterBand(rasBand); band.Fill(GdalUtilConstants.NoDataValue, 0.0); } //band.SetNoDataValue(GdalUtilConstants.NoDataValue); outAlignedRaster.SetProjection(inputShapeSrs); string[] reprojectOptions = { "NUM_THREADS = ALL_CPUS", "WRITE_FLUSH = YES" }; Gdal.ReprojectImage(oldRasterDataset, outAlignedRaster, null, inputShapeSrs, ResampleAlg.GRA_NearestNeighbour, 0.0, 0.0, null, null, reprojectOptions); //flush cache oldRasterDataset.FlushCache(); oldRasterDataset.Dispose(); }
public void GetSupportedGDalDataTypeSet() { var gdalDriverForMapFile = Gdal.GetDriverByName("PCRaster"); var targetTypes = GdalHelper.GetSupportedValueTypes(gdalDriverForMapFile); targetTypes.Should().Contain(DataType.GDT_Byte); targetTypes.Should().Contain(DataType.GDT_Int32); targetTypes.Should().Contain(DataType.GDT_Float32); targetTypes.Should().Have.Count.EqualTo(3); }
/// <summary> /// 改变栅格值 /// </summary> /// <param name="dsm"></param> /// <param name="savePath"></param> public static void editRasterValue(string dsm, string savePath, double doubles = 2) { Gdal.AllRegister(); Dataset inData = Gdal.Open(dsm, Access.GA_ReadOnly); int xSize = inData.RasterXSize; int ySize = inData.RasterYSize; OSGeo.GDAL.Driver dr = Gdal.GetDriverByName("HFA"); Dataset newDs = dr.Create(savePath, xSize, ySize, 1, inData.GetRasterBand(1).DataType, null); double[] GeoTrans = new double[6]; inData.GetGeoTransform(GeoTrans); newDs.SetGeoTransform(GeoTrans); int userSetX = 1000; int userSetY = 1000; int pixelCount = xSize / userSetX + 1; int lineCount = ySize / userSetY + 1; Console.WriteLine("起动单线编辑栅格值,Size为{0}*{1}", xSize, ySize); Console.WriteLine("分块为为{0}*{1},改变值为原来的{2}倍", userSetX, userSetY, doubles); for (int iline = 0; iline < lineCount; iline++) { for (int ipixel = 0; ipixel < pixelCount; ipixel++) { int subXsize = userSetX; int subYsize = userSetY; int offx = subXsize * ipixel; int offy = subYsize * iline; if (ipixel == pixelCount - 1) { subXsize = xSize - subXsize * ipixel - 1; } if (iline == lineCount - 1) { subYsize = ySize - subYsize * iline - 1; } double[] rasterValue = new double[subXsize * subYsize]; inData.GetRasterBand(1).ReadRaster(offx, offy, subXsize, subYsize, rasterValue, subXsize, subYsize, 0, 0); for (int v = 0; v < rasterValue.Length; v++) { rasterValue[v] = rasterValue[v] * doubles; } newDs.GetRasterBand(1).WriteRaster(offx, offy, subXsize, subYsize, rasterValue, subXsize, subYsize, 0, 0); Console.WriteLine("编辑栅格值,已完成:{0}/{1}", iline * ipixel, lineCount * pixelCount); } } newDs.Dispose(); inData.Dispose(); }
public static void Main(string[] args) { if (args.Length != 2) { usage(); } Console.WriteLine(""); try { /* -------------------------------------------------------------------- */ /* Register driver(s). */ /* -------------------------------------------------------------------- */ Gdal.AllRegister(); /* -------------------------------------------------------------------- */ /* Get driver */ /* -------------------------------------------------------------------- */ Driver drv = Gdal.GetDriverByName("GTiff"); if (drv == null) { Console.WriteLine("Can't get driver."); System.Environment.Exit(-1); } Console.WriteLine("Using driver " + drv.LongName); /* -------------------------------------------------------------------- */ /* Open dataset. */ /* -------------------------------------------------------------------- */ Dataset ds = Gdal.Open(args[0], Access.GA_ReadOnly); if (ds == null) { Console.WriteLine("Can't open source dataset " + args[0]); System.Environment.Exit(-1); } string[] options = new string [] { "TILED=YES" }; Dataset dso = drv.CreateCopy(args[1], ds, 0, options, new Gdal.GDALProgressFuncDelegate(ProgressFunc), "Sample Data"); if (dso == null) { Console.WriteLine("Can't create dest dataset " + args[1]); System.Environment.Exit(-1); } } catch (Exception e) { Console.WriteLine("Application error: " + e.Message); } }
public void GetSupportedGdalTargetTypeByDriverAndComponentTypeForBIL() { const string path = @"..\..\..\..\data\RasterData\Bodem.bil"; var driverName = GdalHelper.GetDriverName(path); var valueType = typeof(double); var gdalDriver = Gdal.GetDriverByName(driverName); var dataType = GdalHelper.GetGdalDataType(gdalDriver, valueType); Assert.AreEqual(DataType.GDT_Float32, dataType); }
public static void PutOutput_harvestBACut(string fn, string fn1, double[] wAdfGeoTransform) { StreamWriter fpOutput; int i; int j; string pszFormat = "HFA"; //* Driver poDriver; //* string[] papszMetadata; //* poDriver = Gdal.GetDriverByName(pszFormat); //* if (poDriver == null) //* { Environment.Exit(1); } papszMetadata = poDriver.GetMetadata(""); //* Dataset poDstDS; //* Band outPoBand; //* float cellsize = BoundedPocketStandHarvester.pCoresites.Header[30]; string[] papszOptions = null; //* float[] pafScanline; //* uint[] pintScanline; string pszSRS_WKT = null; //* SpatialReference oSRS = new SpatialReference(null); //* oSRS.SetUTM(11, 1); //* oSRS.SetWellKnownGeogCS("HEAD74"); //* oSRS.ExportToWkt(out pszSRS_WKT); //* pafScanline = new float[BoundedPocketStandHarvester.pCoresites.numRows() * BoundedPocketStandHarvester.pCoresites.numColumns()]; //* poDstDS = poDriver.Create(fn1, BoundedPocketStandHarvester.pCoresites.numColumns(), BoundedPocketStandHarvester.pCoresites.numRows(), 1, DataType.GDT_Float32, papszOptions); //* if (poDstDS == null) { throw new Exception("Img file not be created."); //* } outPoBand = poDstDS.GetRasterBand(1); //* poDstDS.SetGeoTransform(wAdfGeoTransform); //* for (i = BoundedPocketStandHarvester.pCoresites.numRows(); i > 0; i--) { for (j = 1; j <= BoundedPocketStandHarvester.pCoresites.numColumns(); j++) { double tmpBAout = BoundedPocketStandHarvester.pHarvestsites.GetValueHarvestBA(i, j); pafScanline [(BoundedPocketStandHarvester.pCoresites.numRows() - i) * BoundedPocketStandHarvester.pCoresites.numColumns() + j - 1] = (float)BoundedPocketStandHarvester.pHarvestsites.GetValueHarvestBA(i, j); //* } } BoundedPocketStandHarvester.pHarvestsites.clearValueHarvestBA(); outPoBand.WriteRaster(0, 0, BoundedPocketStandHarvester.pCoresites.numColumns(), BoundedPocketStandHarvester.pCoresites.numRows(), pafScanline, BoundedPocketStandHarvester.pCoresites.numColumns(), BoundedPocketStandHarvester.pCoresites.numRows(), 0, 0); //* if (poDstDS != null) { poDstDS.Dispose(); //* } pafScanline = null; }
public bool LatLon_TiffToUTM_Tiff(string inPut, string outPut, int band = 1) { FileInfo inPutFile = new FileInfo(inPut); //입력 파일이 없다면 종료 if (!inPutFile.Exists) { return(false); } else { //입력 파일이 tif / tiff 파일이 아니라면 종료 if (inPutFile.Extension != ".tif" && inPutFile.Extension != ".tiff") { return(false); } } #region Create Tiff Gdal.AllRegister(); Dataset dataset = Gdal.Open(inPut, Access.GA_ReadOnly); //SpatialReference dstt_srs = new SpatialReference(""); //dstt_srs.SetFromUserInput("+proj=utm +zone=21 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"); string t_srs_wkt = "GEOGCS[\"WGS84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS84\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.01745329251994328]]"; //dstt_srs.ExportToWkt(out t_srs_wkt); //SpatialReference src_srs = new SpatialReference(""); //src_srs.SetFromUserInput("+proj=longlat"); string s_srs_wkt = dataset.GetProjectionRef(); //src_srs.ExportToWkt(out s_srs_wkt); Dataset dswarp = Gdal.AutoCreateWarpedVRT(dataset, s_srs_wkt, t_srs_wkt, ResampleAlg.GRA_NearestNeighbour, 0.125); string[] options = null; OSGeo.GDAL.Driver srcDrv = Gdal.GetDriverByName("GTiff"); Dataset dstDs = srcDrv.CreateCopy(outPut, dswarp, 0, options, null, null); //dstDs.SetProjection(dataset.GetProjection()); //double[] geot = new double[6]; //dataset.GetGeoTransform(geot); //dstDs.SetGeoTransform(geot); dstDs.FlushCache(); dstDs.Dispose(); srcDrv.Dispose(); #endregion return(true); }
public static void WritePng(IntPtr data, int dataWidth, int dataHeight, int outputWidth, int outputHeight, string path) { Driver png = Gdal.GetDriverByName("PNG"); Driver mem = Gdal.GetDriverByName("MEM"); using (Dataset memDataSet = mem.Create("", outputWidth, outputHeight, 1, DataType.GDT_UInt16, new string[0])) { memDataSet.WriteRaster(0, 0, outputWidth, outputHeight, data, dataWidth, dataHeight, DataType.GDT_UInt16, 1, new[] { 1 }, 0, 0, 0); Dataset pngDataSet = png.CreateCopy(path, memDataSet, 1, new string[0], null, null); pngDataSet.Dispose(); } }
public static void Main(string[] args) { if (args.Length != 1) { usage(); } byte[] imageBuffer; using (FileStream fs = new FileStream(args[0], FileMode.Open, FileAccess.Read)) { using (BinaryReader br = new BinaryReader(fs)) { long numBytes = new FileInfo(args[0]).Length; imageBuffer = br.ReadBytes((int)numBytes); br.Close(); fs.Close(); } } Gdal.AllRegister(); string memFilename = "/vsimem/inmemfile"; try { Gdal.FileFromMemBuffer(memFilename, imageBuffer); Dataset ds = Gdal.Open(memFilename, Access.GA_ReadOnly); Console.WriteLine("Raster dataset parameters:"); Console.WriteLine(" RasterCount: " + ds.RasterCount); Console.WriteLine(" RasterSize (" + ds.RasterXSize + "," + ds.RasterYSize + ")"); Driver drv = Gdal.GetDriverByName("GTiff"); if (drv == null) { Console.WriteLine("Can't get driver."); System.Environment.Exit(-1); } drv.CreateCopy("sample.tif", ds, 0, null, null, null); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Gdal.Unlink(memFilename); } }