private IRasterBand[] GetBandFromDatasetNames(string[] datasetNames) { if (datasetNames == null || datasetNames.Length == 0) { return(null); } if (_allGdalSubDatasets == null || _allGdalSubDatasets.Length == 0) { return(null); } List <IRasterBand> rasterBands = new List <IRasterBand>(); foreach (string dsName in datasetNames) { string dsPath = GetDatasetFullPath(dsName); if (string.IsNullOrWhiteSpace(dsPath)) { throw new Exception(string.Format("文件中不存在指定的数据集[{0}]{1}", dsName, _provider.fileName)); } Dataset dataset = Gdal.Open(dsPath, _access); IRasterBand[] gdalDatasets = ReadBandsFromDataset(dataset, _provider); rasterBands.AddRange(gdalDatasets); } return(rasterBands.Count == 0 ? null : rasterBands.ToArray()); }
public override string[] Process(IGeographicPoint leftUpper, IGeographicPoint rigthLower, string dataFolder, string resultFolder) { var folderDescription = new LandsatDataDescription(dataFolder); var path = folderDescription; LandsatMetadata metadataFile = JsonHelper.Deserialize <LandsatMetadata>(folderDescription.MetadataMtlJson); TirsThermalConstants thermalConstants = metadataFile.L1MetadataFile.TirsThermalConstants; var cuttedImageInfo = ClipImageHelper.GetCuttedImageInfoByPolygon(folderDescription.Channel10.Raw, new GeographicPolygon { UpperLeft = leftUpper, LowerRight = rigthLower }); using (var ds = Gdal.Open(folderDescription.Channel10.Raw, Access.GA_ReadOnly)) { CalculateTemperature(ds.GetRasterBand(1), metadataFile.L1MetadataFile.RadiometricRescaling.RadianceMultBand11, metadataFile.L1MetadataFile.RadiometricRescaling.RadianceAddBand11, thermalConstants.K1ConstantBand11, thermalConstants.K2ConstantBand11, resultFolder, cuttedImageInfo ); } return(new[] { resultFolder + "\\temperature.png" }); }
/// <summary> /// This should update the palette cached and in the file. /// </summary> /// <param name="value">The color palette.</param> public override void SetColorPalette(IEnumerable <Color> value) { var colorPalette = value as IList <Color> ?? value.ToList(); ColorPalette = colorPalette; _dataset = Gdal.Open(Filename, Access.GA_Update); ColorTable ct = new ColorTable(PaletteInterp.GPI_RGB); int index = 0; foreach (var c in colorPalette) { ColorEntry ce = new ColorEntry { c4 = c.A, c3 = c.B, c2 = c.G, c1 = c.R }; ct.SetColorEntry(index, ce); index++; } using (Band first = _dataset.GetRasterBand(1)) { first.SetRasterColorTable(ct); } }
/// <summary> /// Load media from stream. /// </summary> /// <param name="stream"> /// A <see cref="Stream"/> where the media data is stored. /// </param> /// <param name="criteria"> /// A <see cref="MediaCodecCriteria"/> that specify parameters for loading an media stream. /// </param> /// <returns> /// An <see cref="Image"/> holding the media data. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="stream"/> or <paramref name="criteria"/> is null. /// </exception> public Image Load(Stream stream, ImageCodecCriteria criteria) { if (stream == null) { throw new ArgumentNullException("stream"); } if (criteria == null) { throw new ArgumentNullException("criteria"); } const int BufferBlockSize = 4096; byte[] buffer = new byte[stream.Length]; int bufferOffset = 0, bytesRed; // Read the stream content while ((bytesRed = stream.Read(buffer, bufferOffset, BufferBlockSize)) > 0) { bufferOffset += bytesRed; } GCHandle bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { Gdal.FileFromMemBuffer("/vsimem/GdalLoad", buffer.Length, bufferHandle.AddrOfPinnedObject()); using (Dataset dataset = Gdal.Open("/vsimem/GdalLoad", Access.GA_ReadOnly)) { return(Load(dataset, criteria)); } } finally { // Release virtual path Gdal.Unlink("/vsimem/GdalLoad"); bufferHandle.Free(); } }
/// <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完成"); }
public static Dataset ToMemDataset(this Image image, string memPath = "/vsimem/inmemfile") { Dataset dataset = null; if (image == null) { throw new Exception("image不能为空"); } if (memPath?.StartsWith("/vsimem/") != true) { throw new Exception("memPath必须以“/vsimem/”开头"); } byte[] buffer = null; using (MemoryStream ms = new MemoryStream()) { var format = image.RawFormat.ToString(); if (format.Contains("[ImageFormat:")) { throw new Exception("image格式不正确"); } image.Save(ms, image.RawFormat); buffer = ms.GetBuffer(); } Gdal.FileFromMemBuffer(memPath, buffer); dataset = Gdal.Open(memPath, Access.GA_ReadOnly); return(dataset); }
public static int GetElevationFromLonLat( double longitude, double latitude) { try { Dataset ds = Gdal.Open( GetRasterPath(longitude, latitude), Access.GA_ReadOnly); double[] pGT = new double[6]; ds.GetGeoTransform(pGT); int col = Math.Abs((int)((longitude - pGT[0]) / pGT[1])); int row = Math.Abs((int)((pGT[3] - latitude) / -pGT[5])); Band band = ds.GetRasterBand(1); CPLErr error; // p read block byte int[] pRBB = new int[1]; error = band.ReadRaster(col, row, 1, 1, pRBB, 1, 1, 0, 0); if (pRBB[0] < 0) { pRBB[0] = 0; } band.Dispose(); ds.Dispose(); return(pRBB[0]); } catch (Exception) { return(0); } }
public static double[] GetClippedGeoTransform(string gdalDataset, PixelLims subsetCoords) { if (!System.IO.File.Exists(gdalDataset)) { throw new ArgumentException("File does not exist!"); } Dataset ds = Gdal.Open(gdalDataset, Access.GA_ReadOnly); if (ds == null) { throw new ArgumentException("Can't open " + gdalDataset); } double[] inGT = new double[6]; ds.GetGeoTransform(inGT); var topLeftLongIn = inGT[0]; var topLeftLatIn = inGT[3]; var resX = inGT[1]; var resY = inGT[5]; if (inGT[2] != 0.0 || inGT[4] != 0) { throw new InvalidOperationException("Only datasets with zero skew parameters (i.e. those aligned north-south) are supported"); } var topLeftLongOut = topLeftLongIn + subsetCoords.WestPixelCoord * resX; var topLeftLatOut = topLeftLatIn + subsetCoords.NorthPixelCoord * resY; var clippedGT = new double[] { topLeftLongOut, resX, 0.0, topLeftLatOut, 0.0, resY }; return(clippedGT); }
public override byte[] GetTileBytes(int level, int row, int col) { double xmin, ymin, xmax, ymax; Utility.CalculateBBox(TilingScheme.TileOrigin, TilingScheme.LODs[level].Resolution, TilingScheme.TileRows, TilingScheme.TileCols, row, col, out xmin, out ymin, out xmax, out ymax); using (Dataset ds = Gdal.Open(this.Path, Access.GA_ReadOnly)) { //Dataset ds = Services[serviceName].RasterDataset; //reprojection if necessary //TODO:reproject raster double[] adfGeoTransform = new double[6]; ds.GetGeoTransform(adfGeoTransform); double upperLeftPixelX, upperLeftPixelY, bottomRightPixelX, bottomRightPixelY; GDALConvertGeoCoordsToPixels(adfGeoTransform, xmin, ymax, out upperLeftPixelX, out upperLeftPixelY); GDALConvertGeoCoordsToPixels(adfGeoTransform, xmax, ymin, out bottomRightPixelX, out bottomRightPixelY); int tileRows = this.TilingScheme.TileRows; int tileCols = this.TilingScheme.TileCols; using (Bitmap bitmap = ReadRasterByGDAL(ds, upperLeftPixelX, upperLeftPixelY, bottomRightPixelX, bottomRightPixelY, tileCols, tileRows)) { if (bitmap == null) { return(null); } //convert bitmap to byte[] using (MemoryStream ms = new MemoryStream()) { bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Flush(); return(ms.GetBuffer()); } } } }
public void GetOlines(string inDataPath, string _outDSpath, string OutShpPath, double ImprotLevel = 80) { Gdal.AllRegister(); qthread = new QThread(OutShpPath); Dataset _inDataset = Gdal.Open(inDataPath, Access.GA_ReadOnly); Dataset _outDataset = Gdal.Open(_outDSpath, Access.GA_ReadOnly); AutoResetEvent autoRE = new AutoResetEvent(false); int iCount = 0, Maxcnt = GetCutNumberOfImg(inDataPath); for (int i = 0; i < Maxcnt; i++) { CutData data = new CutData(inDataPath, _outDSpath, OutShpPath, i, ImprotLevel); Thread th = new Thread((tt) => { TKData(tt); iCount++; if (iCount == Maxcnt) { autoRE.Set(); } }); th.Name = "thNM_" + i.ToString(); th.Start(data); } autoRE.WaitOne(); qthread.Close(); }
public static bool WritePartTiff(string Filename, float[] Data, PixelLims WriteShape) { var ds = Gdal.Open(Filename, Access.GA_Update); var band = ds.GetRasterBand(1); var fileShapeX = ds.RasterXSize; var fileShapeY = ds.RasterYSize; var writeSizeX = WriteShape.EastPixelCoord - WriteShape.WestPixelCoord; var writeSizeY = WriteShape.SouthPixelCoord - WriteShape.NorthPixelCoord; if (WriteShape.SouthPixelCoord > fileShapeY || WriteShape.EastPixelCoord > fileShapeX || writeSizeX * writeSizeY != Data.Length) { return(false); } int dataBlockSizeX, dataBlockSizeY; band.GetBlockSize(out dataBlockSizeX, out dataBlockSizeY); if (dataBlockSizeX != writeSizeX || dataBlockSizeY != writeSizeY || WriteShape.WestPixelCoord % dataBlockSizeX != 0 || WriteShape.NorthPixelCoord % dataBlockSizeY != 0) { // only for testing, we will allow non-whole block writing eventually return(false); } band.WriteRaster( (int)WriteShape.WestPixelCoord, (int)WriteShape.NorthPixelCoord, (int)writeSizeX, (int)writeSizeY, Data, (int)writeSizeX, (int)writeSizeY, 0, 0); band.FlushCache(); ds.FlushCache(); return(true); }
/// <summary> /// 获取图像分块儿数 /// </summary> /// <param name="imgPath"></param> /// <returns></returns> private int GetCutNumberOfImg(string imgPath) { Dataset _inDataset = Gdal.Open(imgPath, Access.GA_ReadOnly); int xTimes = (_inDataset.RasterXSize - 300) / 500; int xRemainder = (_inDataset.RasterXSize - 300) % 500; int yTimes = (_inDataset.RasterYSize - 300) / 500; int yRemainder = (_inDataset.RasterYSize - 300) % 500; int ax = xTimes, by = yTimes; if (xTimes == 0) { xRemainder = _inDataset.RasterXSize; } if (yTimes == 0) { yRemainder = _inDataset.RasterYSize; } if (xRemainder > 10) { ax++; } if (yRemainder > 10) { by++; } int Maxcnt = ax * by; return(Maxcnt); }
private async void GetOlines00(string inDataPath, string _outDSpath, string OutShpPath, double ImprotLevel = 80) { Gdal.AllRegister(); Dataset _inDataset = Gdal.Open(inDataPath, Access.GA_ReadOnly); Dataset _outDataset = Gdal.Open(_outDSpath, Access.GA_ReadOnly); int iCount = 0, Maxcnt = GetCutNumberOfImg(inDataPath); for (int i = 0; i < Maxcnt; i++) { CutData data = new CutData(inDataPath, _outDSpath, OutShpPath, i, ImprotLevel); await Task.Run(() => { TKData(data); iCount++; if (iCount == Maxcnt) { asyRE.Set(); } }); } }
public static List <GeographicPoint> GetGeographicPointsByPointsIndexes(List <Point> points, string filename, GeographicPolygon polygon) { using (var ds = Gdal.Open(filename, Access.GA_ReadOnly)) { var georgrapicPoints = new List <GeographicPoint>(); double[] geotransform = new double[6]; ds.GetGeoTransform(geotransform); var utmPolygon = Helper.ConvertGeographicPolygonToUtm(polygon, ds); var xinit = utmPolygon.UpperLeft.Easting; //utm-northing upperleft point var yinit = utmPolygon.UpperLeft.Northing; //размер пикселя var xsize = geotransform[1]; var ysize = geotransform[5]; var utmPoints = points.Select(p => new UtmPoint { Easting = xinit + xsize * p.X, Northing = yinit - ysize * p.Y } ); georgrapicPoints = utmPoints.Select(p => Helper.ConvertUtmPointToGeographic(p, ds)).ToList(); return(georgrapicPoints); } }
public static bool EcwToTiff(string inputFile, string outputFile, GDALTranslateOptions translateOptions, Gdal.GDALProgressFuncDelegate progressFuncDelegate) { bool result = false; Dataset dataset = null; try { Gdal.PushErrorHandler(new Gdal.GDALErrorHandlerDelegate(GdalHandlers.ErrorHandler)); dataset = Gdal.Open(inputFile, Access.GA_ReadOnly); Gdal.PopErrorHandler(); if (dataset != null) { result = Translate(dataset, outputFile, translateOptions, progressFuncDelegate); } } catch (Exception ex) { //LoggerManager.WriteErrorLog(ex.Message); } finally { if (dataset != null) { dataset.FlushCache(); dataset.Dispose(); } } return(result); }
private void OpenGdalDataset(string path) { if (IsOpen) { Close(); } RegisterGdal(); CheckAndFixHeaders(path); gdalDataset = Gdal.Open(path.ToLower(), Access.GA_Update); SetDriver(path); /* * var geoTrans = new double[6]; * gdalDataset.GetGeoTransform(geoTrans); * var transform = new RegularGridGeoTransform(geoTrans); * * int sizeX = gdalDataset.RasterXSize; * int sizeY = gdalDataset.RasterYSize; * * // double deltaX = sizeX/gdalDataset.RasterCount; * double deltaX = transform.HorizontalPixelResolution; * double deltaY = transform.VerticalPixelResolution; * * * var origin = new Coordinate(transform.Left, transform.Top - deltaY * sizeY); * /yValues = GetValuesArray(deltaY, sizeY, origin.Y); * /xValues = GetValuesArray(deltaX, sizeX, origin.X); */ }
/// <summary> /// Opens the given file. /// </summary> /// <param name="fileName">File that gets opened.</param> /// <returns>Opened file as data set.</returns> public static Dataset Open(string fileName) { Dataset dataset = null; if (string.IsNullOrEmpty(fileName)) { return(dataset); } try { dataset = Gdal.Open(fileName, Access.GA_Update); } catch { try { dataset = Gdal.Open(fileName, Access.GA_ReadOnly); } catch (Exception ex) { throw new GdalException(ex.ToString()); } } return(dataset); }
/// <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 static void Main(string[] args) { if (args.Length != 3) { usage(); } Gdal.AllRegister(); GDALWarpAppOptions options = new GDALWarpAppOptions(args[1].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); string[] dstNames = args[2].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Dataset[] ds = new Dataset[dstNames.Length]; for (int i = 0; i < dstNames.Length; i++) { ds[i] = Gdal.Open(dstNames[i], Access.GA_ReadOnly); } Dataset dso = Gdal.Warp(args[0], ds, options, new Gdal.GDALProgressFuncDelegate(ProgressFunc), "Sample Data"); if (dso == null) { Console.WriteLine("Can't create dest dataset " + args[1]); System.Environment.Exit(-1); } }
/// <summary> /// Saves a bitmap of data as a continuous block into the specified location. /// This always writes to the base image, and not the overviews. /// </summary> /// <param name="value">The bitmap value to save.</param> /// <param name="xOffset">The zero based integer column offset from the left</param> /// <param name="yOffset">The zero based integer row offset from the top</param> public override void WriteBlock(Bitmap value, int xOffset, int yOffset) { if (_dataset == null) { // This will fail if write access is not allowed, but just pass the // exception back up the stack. _dataset = Gdal.Open(Filename, Access.GA_Update); } Band first = _dataset.GetRasterBand(1); if (BandType == ImageBandType.PalletCoded) { WritePaletteBuffered(value, xOffset, yOffset, first); } if (BandType == ImageBandType.Gray) { WriteGrayIndex(value, xOffset, yOffset, first); } if (BandType == ImageBandType.RGB) { WriteRgb(value, xOffset, yOffset, first, _dataset); } if (BandType == ImageBandType.ARGB) { WriteArgb(value, xOffset, yOffset, first, _dataset); } first.Dispose(); }
/// <summary> /// 展现Img /// </summary> /// <param name="filename">img文件</param> /// <param name="Width">显示区域宽度</param> /// <param name="Height">需要显示高度</param> /// <returns>返回Bitmap对象</returns> public Bitmap ImageShow(string filename, int Width, int Height) { // 为了支持中文路径,请添加下面这句代码 OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); // 为了使属性表字段支持中文,请添加下面这句 OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", ""); OSGeo.GDAL.Gdal.AllRegister(); OSGeo.GDAL.Dataset ds = Gdal.Open(filename, Access.GA_ReadOnly); if (ds == null) { MessageBox.Show("影像打开失败"); return(null); } Rectangle pictureRect = new Rectangle(); pictureRect.X = 0; pictureRect.Y = 0; pictureRect.Width = Width; pictureRect.Height = Height; int[] disband = { 3, 2, 1 }; Bitmap bitmap = GetImage(ds, pictureRect, disband); //遥感影像构建位图 return(bitmap); // pictureBox1.Image = bitmap; //将位图传递给PictureBox控件进行显示 }
private void openMsi1_Click(object sender, EventArgs e) { Gdal.AllRegister(); OpenFileDialog ofd = new OpenFileDialog(); //允许打开的文件格式 ofd.Filter = "Erdas Imagine (*.img)|*.img|" + "GeoTiff (*.tif *.tiff)|*.tif;*.tiff|" + "HDF (*.hdf *.h5 *he5)|*.hdf;*.h5;*he5|" + "位图文件 (*.bmp)|*.bmp|" + "Graphics Interchange Format (*.gif)|*.gif|" + "JPEG (*.jpg *.jpeg)|*.jpg;*.jpeg|" + "Portable Network Graphics (*.png)|*.png|" + "所有文件|*.*"; if (ofd.ShowDialog() == DialogResult.OK) { file1 = ofd.FileName; ds1 = Gdal.Open(file1, Access.GA_ReadOnly); if (ds1.RasterCount < 3) { MessageBox.Show("不是多波段影像!\n请重新选择", "Error"); file1 = null; } } }
private bool CreatePyramids(string filename) { Gdal.SetConfigOption("USE_RRD", "YES"); Dataset ds = Gdal.Open(filename, Access.GA_Update); Driver drv = ds.GetDriver(); // System.Type szDriver = drv.ShortName.GetType(); int iWidth = ds.RasterXSize; int iHeight = ds.RasterYSize; int iPixelNum = iWidth * iHeight; //图像中的总像元个数 int iTopNum = 4096; //顶层金字塔大小,64*64 int iCurNum = iPixelNum / 4; int[] anLevels = new int[1024]; int nLevelCount = 0; //金字塔级数 do { anLevels[nLevelCount] = Convert.ToInt32(Math.Pow(2.0, nLevelCount + 2)); nLevelCount++; iCurNum /= 4; } while (iCurNum > iTopNum); int[] levels = new int[nLevelCount]; for (int a = 0; a < nLevelCount; a++) { levels[a] = anLevels[a]; } int ret = ds.BuildOverviews("nearest", levels); ds.Dispose(); drv.Dispose(); return(true); }
private void ReadHeader() { try { _dataset = Gdal.Open(Filename, Access.GA_Update); } catch { try { _dataset = Gdal.Open(Filename, Access.GA_ReadOnly); } catch (Exception ex) { throw new GdalException(ex.ToString()); } } Init(_dataset.RasterXSize, _dataset.RasterYSize); NumBands = _dataset.RasterCount; WorldFile = new WorldFile { Affine = new double[6] }; double[] test = new double[6]; _dataset.GetGeoTransform(test); Bounds = new RasterBounds(Height, Width, test); WorldFile.Affine = test; DoClose(); }
public FY3AASOandASLProvider(string fileName, byte[] header1024, IGeoDataDriver driver, params object[] args) : base(fileName, driver) { _fileName = fileName; _args = args; using (Dataset dataset = Gdal.Open(fileName, Access.GA_ReadOnly)) { GDALHelper.GetDatasetAttributes(dataset, _attributes); } Dictionary <string, string> allGdalSubDatasets = this.Attributes.GetAttributeDomain("SUBDATASETS"); _allGdalSubDatasets = RecordAllSubDatasetNames(allGdalSubDatasets); _coordEnvelope = TrySetGeoInfo(); _selectedsets = TryGetSelectedSets(); TryCreateBandProvider(); _bandCount = _rasterBands.Count; _dataType = _rasterBands[0].DataType; _width = _rasterBands[0].Width; _height = _rasterBands[0].Height; _spatialRef = SpatialReference.GetDefault(); _coordType = _spatialRef.ProjectionCoordSystem != null ? enumCoordType.PrjCoord : enumCoordType.GeoCoord; _resolutionX = (float)(_coordEnvelope.Width / (_width)); _resolutionY = (float)(_coordEnvelope.Height / (_height)); if (_dataIdentify != null) { _dataIdentify.OrbitDateTime = IceConDataProvider.TryGetFileDate(Path.GetFileName(fileName)); } }
public static float[,] GenPopData() { string path = System.IO.Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.FullName; var yemData = Gdal.Open(path + "\\Population.tif", Access.GA_ReadOnly); var yemPopData = yemData.GetRasterBand(1); int width = yemPopData.XSize; int height = yemPopData.YSize; float[] buffer = new float[width * height]; yemPopData.ReadRaster(0, 0, width, height, buffer, width, height, 0, 0); var popArray = new float[width, height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { popArray[i, j] = buffer[i + j * width]; } } Console.WriteLine("Pop Data Generated"); return(popArray); }
/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <param name="header1024"></param> /// <param name="driver"></param> /// <param name="args"> /// 可扩展的参数信息,每对参数都采用key=value的形式。 /// 1、数据集,采用逗号分隔的形式加入默认所选择的波段。 /// 例如:datasets=VIRR_1Km_LST[,...] /// 2、投影方式,采用proj4字符串的形式 /// 例如:proj4= /// 3、其他待扩展的参数信息 /// 坐标信息:geoinfo=1,2,3,4,5,6//其中1,2,3,4,5,6分辨代表:minX,maxX,minY,maxY,resolutionX,resolutionY; /// 经纬度数据集:geodatasets=Longitude,Latitude//该数据对轨道数据有效。 /// </param> public HdfRasterDataProvider(string fileName, byte[] header1024, IGeoDataDriver driver, params object[] args) : base(fileName, driver) //: base(fileName, driver) { _args = args; TryParseArgs(); using (Dataset _dataset = Gdal.Open(fileName, Access.GA_ReadOnly)) { GDALHelper.GetDatasetAttributes(_dataset, _attributes); //数据集仅有一个数据集,一个通道 if (_dataset.RasterCount == 1) { //GDAL对于只有一个数据集的HDF数据,SUBDATASETS属性值是空的,这里尝试手动设置下 TrySetGDALSUBDATASETS(_datasets); } } //...可以在此添加投影等信息 TryCreateBandProvider(fileName, header1024, _datasets, _attributes.GetAttributeDomain("SUBDATASETS")); //_bandCount = _dataset.RasterCount; _bandCount = _rasterBands.Count; TryGetDatTypeOfProvider(); TryGetSizeOfProvider(); TryCreateSpatialRef(); TryCreateCoordTransform(); TrySetEnvelopeAndResolutions(); }
public static int[,] GenAdminData() { string path = System.IO.Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.FullName; var adminData = Gdal.Open(path + "\\Admin1.tif", Access.GA_ReadOnly); var admin1Data = adminData.GetRasterBand(1); int width = admin1Data.XSize; int height = admin1Data.YSize; int[] buffer = new int[width * height]; admin1Data.ReadRaster(0, 0, width, height, buffer, width, height, 0, 0); var admin1Array = new int[width, height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { admin1Array[i, j] = buffer[i + j * width]; } } Console.WriteLine("Admin Data Generated"); return(admin1Array); }
/// <summary> /// Saves a bitmap of data as a continuous block into the specified location. /// This always writes to the base image, and not the overviews. /// </summary> /// <param name="value">The bitmap value to save.</param> /// <param name="xOffset">The zero based integer column offset from the left</param> /// <param name="yOffset">The zero based integer row offset from the top</param> public override void WriteBlock(Bitmap value, int xOffset, int yOffset) { if (_dataset == null) { // This will fail if write access is not allowed, but just pass the // exception back up the stack. _dataset = Gdal.Open(Filename, Access.GA_Update); } using (var first = _dataset.GetRasterBand(1)) { switch (BandType) { case ImageBandType.PalletCoded: WritePaletteBuffered(value, xOffset, yOffset, first); break; case ImageBandType.Gray: WriteGrayIndex(value, xOffset, yOffset, first); break; case ImageBandType.RGB: WriteRgb(value, xOffset, yOffset, first, _dataset); break; case ImageBandType.ARGB: WriteArgb(value, xOffset, yOffset, first, _dataset); break; } } }
/// <summary> /// Runs GdalWarp with passed parameters /// </summary> /// <param name="inputFilePath">Input GeoTiff's path</param> /// <param name="outputFilePath">Output file's path</param> /// <param name="options">Array of string parameters /// <remarks><para/>See <see cref="ConvertCoordinateSystemOptions"/> field for /// more info</remarks></param> /// <param name="progress">GdalWarp's progress /// <remarks><para/><see langword="null"/> by default</remarks></param> /// <exception cref="ArgumentNullException"/> public static Task WarpAsync(string inputFilePath, string outputFilePath, string[] options, IProgress <double> progress = null) { #region Preconditions checks CheckHelper.CheckFile(inputFilePath); CheckHelper.CheckFile(outputFilePath, false); CheckHelper.CheckDirectory(Path.GetDirectoryName(outputFilePath)); if (options == null || options.Length <= 0) { throw new ArgumentNullException(nameof(options)); } #endregion Gdal.GDALProgressFuncDelegate callback = GdalProgress; _gdalProgress = progress; // Initialize Gdal, if needed ConfigureGdal(); return(Task.Run(() => { using Dataset inputDataset = Gdal.Open(inputFilePath, Access.GA_ReadOnly); using Dataset resultDataset = Gdal.Warp(outputFilePath, new[] { inputDataset }, new GDALWarpAppOptions(options), callback, string.Empty); })); }