static void Main()
    {
        MapFigApplication api = new MapFigApplication("http://Studio URL.com", "6URWZCuYcPdQEgRYH4ZiaYLx4QWXCLwI");

        try
        {

            /*
		    String request = "ogr2ogr"; // gdal_translate, ogr2ogr, ogrinfo
		    String options = "-f \"GeoJSON\""; // optional for request = ogrinfo
		    String sourceFileURL = "https://developers.google.com/kml/documentation/KML_Samples.kml";
		    String targetFileExtension = "json"; // (not required for request = ogrinfo)
		    */
            String request = "ogrinfo"; // gdal_translate, ogr2ogr, ogrinfo
            String options = "";
            String sourceFileURL = "https://developers.google.com/kml/documentation/KML_Samples.kml";
            String targetFileExtension = "json"; // (not required for request = ogrinfo)


            Gdal gdal = new Gdal(request, options, sourceFileURL, targetFileExtension);
            String output = api.getGDALData(gdal);

            Console.WriteLine(output);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
Example #2
0
 private void EnsureDatasetOpen()
 {
     if (_dataset == null)
     {
         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());
             }
         }
     }
 }
Example #3
0
        /// <summary>
        /// Reads the metadata from a file.  NOTE: this is a synchronous call.
        /// </summary>
        /// <param name="fullPath">the file to read the metadata from</param>
        /// <returns>the RasterInfo for that file</returns>
        public static RasterInfo CreateFromMapFile(string fullPath)
        {
            var rasterInfo = new RasterInfo(fullPath);

            using (var dataset = Gdal.OpenShared(fullPath, Access.GA_ReadOnly))
            {
                rasterInfo.ImageSize     = new Size(dataset.RasterXSize, dataset.RasterYSize);
                rasterInfo.NumberOfBands = dataset.RasterCount;
                rasterInfo.Projection    = dataset.GetProjection();
                rasterInfo.MapArea       = CalculateMapArea(dataset);
            }

            Preprocessor pre = new Preprocessor();

            foreach (int zoomLevel in Enumerable.Range(0, 5))
            {
                pre.ProjectAndTile(rasterInfo, zoomLevel, null);
            }

            return(rasterInfo);
        }
Example #4
0
        public void CreateQuicklookInDirectorySquare(/*object sender, DoWorkEventArgs e*/)
        {
            try
            {
                Gdal.AllRegister();
            }
            catch
            {
                MessageBox.Show("Что-то не так с библиотекой gdal");
            }

            GoToDirectories(pathToPicture, "square");

            ProgressDialog.CloseProgressWindow();

            if (isCanceled)//удаляем файлы, если отменили создание квиклука
            {
                isCanceled = false;
                DeleteFiles();
            }
        }
Example #5
0
        public void Open(String filePath)
        {
            GdalConfiguration.ConfigureGdal();
            GdalConfiguration.ConfigureOgr();

            dataset = Gdal.Open(filePath, Access.GA_ReadOnly);
            if (dataset == null)
            {
                Console.WriteLine("Can't open " + filePath);
                Environment.Exit(-1);
            }

            rasterDatas = new List <RasterData>();
            for (int i = 1; i <= dataset.RasterCount; i++)
            {
                Band band = dataset.GetRasterBand(i);
                rasterDatas.Add(new RasterData(band));
            }

            BuildOverview();
        }
Example #6
0
        public void CreateQuicklookInDirectoryPercent(/*object sender, DoWorkEventArgs e*/) //ещё проекции и др. //дописать, как предыдущую ф-ю
        {
            try
            {
                Gdal.AllRegister();
            }
            catch
            {
                MessageBox.Show("Что-то не так с библиотекой gdal");
            }

            GoToDirectories(pathToPicture, "percent");

            ProgressDialog.CloseProgressWindow();

            if (isCanceled) //удаляем файлы, если отменили создание квиклука
            {
                isCanceled = false;
                DeleteFiles();
            }
        }
Example #7
0
        public void readBed(short[] elevation)
        {
            String inFileBed = @"data\elevation\ETOPO1_Bed_g_geotiff.tif";

            Dataset dsBed = Gdal.Open(inFileBed, Access.GA_ReadOnly);
            Band    baBed = dsBed.GetRasterBand(1);

            Console.WriteLine("Elevation File: " + inFileBed);

            // Get the width and height of the Dataset - assuming all sizes the same
            int width  = baBed.XSize;
            int height = baBed.YSize;

            short[] elevation_deviation      = new short[width * height];
            byte[]  elevation_deviation_type = new byte[width * height];

            baBed.ReadRaster(0, 0, width, height, elevation_deviation, width, height, 0, 0);

            // TODO create the deviation separatelly and save to file. To be loaded as elevation_deviation...
            getIceDeviation(elevation, elevation_deviation, elevation_deviation, elevation_deviation_type);
        }
        private void openPan1_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)
            {
                file2 = ofd.FileName;
                ds2   = Gdal.Open(file2, Access.GA_ReadOnly);
            }
        }
Example #9
0
        void getDemH(string demPath, List <Point> mapP)
        {
            Gdal.AllRegister();
            Dataset ds = Gdal.Open(demPath, Access.GA_ReadOnly);

            double[] geoTrans = new double[6];
            ds.GetGeoTransform(geoTrans);
            Band band = ds.GetRasterBand(1);

            for (int i = 0; i < mapP.Count; i++)
            {
                double x = mapP[i].X;
                double y = mapP[i].Y;
                int    xoff, yoff;
                Tools.geoToImageSpace(geoTrans, x, y, out xoff, out yoff);
                double[] values = new double[1];
                band.ReadRaster(xoff, yoff, 1, 1, values, 1, 1, 0, 0);
                mapP[i].Z = (float)values[0];
            }
            ds.Dispose();
        }
        /// <summary>
        /// Reproject a raster.
        /// Working with errors
        /// </summary>
        /// <param name="InputFilePath"></param>
        /// <param name="OutputFilePath"></param>
        /// <param name="EPSG">output EPSG</param>
        public static void RasterReprojection(string InputFilePath, string OutputFilePath, int EPSG)
        {
            // TODO: Check for errors!
            var sr = new OSGeo.OSR.SpatialReference(null);

            sr.ImportFromEPSG(EPSG);
            sr.ExportToWkt(out var srs_wkt, null);

            // reproject raster and save to EHdr
            using (var srcDs = Gdal.Open(InputFilePath, Access.GA_ReadOnly))
                using (var vrt = Gdal.AutoCreateWarpedVRT(srcDs, srcDs.GetProjectionRef(), srs_wkt, ResampleAlg.GRA_Average, 0)) {
                    var OutDirver = srcDs.GetDriver();
                    OutDirver.CreateCopy(OutputFilePath, vrt, 1, null, GDalProgress, "Raster Reprojection");
                }
            //using( var MemDirver = Gdal.GetDriverByName("MEM"))

            //using( var bilDirver = srcDs.GetDriver() Gdal.GetDriverByName("EHdr"))
            //using( var bilfile = bilDirver.CreateCopy("lo que sea/asd/", vrt, 1, null,null, null))

            return;
        }
Example #11
0
        Band getBand(String file)
        {
            /* -------------------------------------------------------------------- */
            /*      Open dataset.                                                   */
            /* -------------------------------------------------------------------- */
            Dataset ds = Gdal.Open(file, Access.GA_ReadOnly);

            // Console.WriteLine("Raster dataset parameters:");
            // Console.WriteLine("  Projection: " + ds.GetProjectionRef());
            // Console.WriteLine("  RasterCount: " + ds.RasterCount);
            // Console.WriteLine("  RasterSize (" + ds.RasterXSize + "," + ds.RasterYSize + ")");

            Band band = ds.GetRasterBand(1);

            // Console.WriteLine("Band " + 1 + " :");
            // Console.WriteLine("   DataType: " + band.DataType);
            // Console.WriteLine("   Size (" + band.XSize + "," + band.YSize + ")");
            // Console.WriteLine("   PaletteInterp: " + band.GetRasterColorInterpretation().ToString());

            return(band);
        }
Example #12
0
        /// <summary>
        /// 读取DEM
        /// </summary>
        /// <param name="dempath"></param>
        public void ReadDEM(string dempath)
        {
            // 为了支持中文路径
            Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
            // 为了使属性表字段支持中文
            Gdal.SetConfigOption("SHAPE_ENCODING", "");

            Gdal.AllRegister();
            ds = Gdal.Open(dempath, Access.GA_ReadOnly);

            //栅格数据长宽
            XSize = ds.RasterXSize;
            YSize = ds.RasterYSize;

            //像元大小
            geoTransform = new double[6];
            ds.GetGeoTransform(geoTransform);
            cellsize = geoTransform[1];

            demBand = ds.GetRasterBand(1); // 获取第一个band
        }
Example #13
0
        public void CreateQuicklookOneImagePercent(/*object sender, DoWorkEventArgs e*/) //ещё проекции и др.
        {
            ProgressDialog.SetImageName(pathToPicture, 1, 0);

            Console.WriteLine(pathToPicture);

            outputFile  = pathToQuicklookCatalog;
            outputFile += pathToPicture.Substring(pathToPicture.LastIndexOf(@"\"));
            outputFile  = outputFile.Replace("tif", format);

            if (IsFileInCatalog(outputFile)) //проверяем, есть ли в каталоге квиклуков это изображение
            {
                if (!overwriteImage)
                {
                    return;
                }
            }

            Console.WriteLine(outputFile);

            try
            {
                Gdal.AllRegister();
            }
            catch
            {
                MessageBox.Show("Что-то не так с библиотекой gdal");
            }

            CreateImage(); //создаём изображение

            ProgressDialog.SetImageName(pathToPicture, 1, 1);
            ProgressDialog.CloseProgressWindow();

            if (isCanceled)//удаляем файлы, если отменили создание квиклука
            {
                isCanceled = false;
                DeleteFiles();
            }
        }
Example #14
0
        [STAThread]        //required because we may be creating a GUI
        public static void Main(string[] args)
        {
            //initialize GDAL
            Gdal.AllRegister();
            //suppress warnings reported by GDAL (erroneously reports warnings because GDAL fails to create useless auxiliary files during processing)
            Gdal.SetErrorHandler(null);

            if (args.Length == 0)              //no arguments specified, so start GUI
            //hide console if we're using a GUI and the window belongs to this program (i.e. has an empty console)
            {
                if (Console.CursorLeft == 0 && Console.CursorTop == 0)
                {
                    IntPtr handle = GetConsoleWindow();
                    ShowWindow(handle, SW_HIDE);
                }

                //run GUI
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm());

                return;         //exit after GUI closes
            }
            else                //arguments were specified, so run program as console command
                                //parse input arguments into a convenient form (ToLookup allows duplicate keys)
            {
                CommandArgField[] ops = CommandUtilities.parseArgs(args);
                Lookup <string, CommandArgField> lup = (Lookup <string, CommandArgField>)ops.ToLookup(p => p.argname);

                //display usage info and quit if -help specified
                if (lup.Contains("-help") == true)
                {
                    printHelp();
                    return;
                }

                //run file calibration
                runConvertCommand(lup);
            }
        }
Example #15
0
        Image <Gray, ushort>[] bantsimg_16(string open)
        {
            Thread thr = new Thread(new ThreadStart(firstwork));

            Gdal.AllRegister();
            Dataset data_igdal = Gdal.Open(open, Access.GA_ReadOnly);

            Band[] bants_gdal = new Band[data_igdal.RasterCount];
            int    rows       = data_igdal.RasterXSize;
            int    cols       = data_igdal.RasterYSize;

            max_progress = cols * data_igdal.RasterCount;
            thr.Start();
            thr.Join();
            int band_count = data_igdal.RasterCount;
            int i, j, bantindeks, k;

            Image <Gray, ushort>[] bantsimg = new Image <Gray, ushort> [data_igdal.RasterCount];
            for (bantindeks = 0; bantindeks < data_igdal.RasterCount; bantindeks++)
            {
                k = 0;
                bants_gdal[bantindeks] = data_igdal.GetRasterBand(bantindeks + 1);
                int[] rasterValues_gdal = new int[rows * cols];
                ushort[,,] ushort_img = new ushort[cols, rows, 1];
                bants_gdal[bantindeks].ReadRaster(0, 0, rows, cols, rasterValues_gdal, rows, cols, 0, 0);
                for (i = 0; i < cols; i++)
                {
                    for (j = 0; j < rows; j++)
                    {
                        ushort_img[i, j, 0] = Convert.ToUInt16(rasterValues_gdal[k]);
                        k = k + 1;
                    }
                    thr = new Thread(new ThreadStart(secondwork));
                    thr.Start();
                    thr.Join();
                }
                bantsimg[bantindeks] = new Image <Gray, ushort>(ushort_img);
            }
            return(bantsimg);
        }
Example #16
0
        /// <summary>
        /// 设置环境变量
        /// </summary>
        public static void SetEnvironmentVariables()
        {
            //  AppDomain.CurrentDomain.AppendPrivatePath(GDAL_CSHARP);
            //  AppDomain.CurrentDomain.AppendPrivatePath(GDAL_CORE);

            if (string.IsNullOrEmpty(GDAL_CORE))
            {
                throw new Exception("没有配置环境变量‘GDAL_CORE’");
            }
            if (string.IsNullOrEmpty(GDAL_APP))
            {
                throw new Exception("没有配置环境变量‘GDAL_APP’");
            }
            if (string.IsNullOrEmpty(GDAL_DATA))
            {
                throw new Exception("没有配置环境变量‘GDAL_DATA’");
            }
            if (string.IsNullOrEmpty(GDAL_CSHARP))
            {
                throw new Exception("没有配置环境变量‘GDAL_CSHARP’");
            }
            string path     = Environment.GetEnvironmentVariable("Path");
            string gdalPath = string.Format("{0};{1};{2}", GDAL_CORE, GDAL_APP, GDAL_CSHARP);

            if (string.IsNullOrEmpty(path))
            {
                path = gdalPath;
            }
            else
            {
                path = string.Format("{0};{1}", path, gdalPath);
            }
            Environment.SetEnvironmentVariable("Path", path, EnvironmentVariableTarget.Process);
            Environment.SetEnvironmentVariable("GDAL_DATA", GDAL_DATA, EnvironmentVariableTarget.Process);
            //Environment.SetEnvironmentVariable("NLS_LANG", Constant.NLS_LANG,
            //EnvironmentVariableTarget.Process);

            Gdal.AllRegister();
            Ogr.RegisterAll();
        }
Example #17
0
        /// <summary>
        /// Construction of Gdal/Ogr
        /// </summary>
        static GdalConfiguration()
        {
            var executingAssemblyFile = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath;
            var executingDirectory    = Path.GetDirectoryName(executingAssemblyFile);

            if (string.IsNullOrEmpty(executingDirectory))
            {
                throw new InvalidOperationException("cannot get executing directory");
            }


            var gdalPath   = Path.Combine(executingDirectory, "gdal");
            var nativePath = Path.Combine(gdalPath, GetPlatform());

            // Prepend native path to environment path, to ensure the
            // right libs are being used.
            var path = Environment.GetEnvironmentVariable("PATH");

            path = nativePath + ";" + Path.Combine(nativePath, "plugins") + ";" + path;
            Environment.SetEnvironmentVariable("PATH", path);

            // Set the additional GDAL environment variables.
            var gdalData = Path.Combine(gdalPath, "data");

            Environment.SetEnvironmentVariable("GDAL_DATA", gdalData);
            Gdal.SetConfigOption("GDAL_DATA", gdalData);

            var driverPath = Path.Combine(nativePath, "plugins");

            Environment.SetEnvironmentVariable("GDAL_DRIVER_PATH", driverPath);
            Gdal.SetConfigOption("GDAL_DRIVER_PATH", driverPath);

            Environment.SetEnvironmentVariable("GEOTIFF_CSV", gdalData);
            Gdal.SetConfigOption("GEOTIFF_CSV", gdalData);

            var projSharePath = Path.Combine(gdalPath, "share");

            Environment.SetEnvironmentVariable("PROJ_LIB", projSharePath);
            Gdal.SetConfigOption("PROJ_LIB", projSharePath);
        }
Example #18
0
        private void Functions_CollectionChanging(object sender, NotifyCollectionChangedEventArgs e)
        {
            if ((e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Replace) &&
                e.Item is IRegularGridCoverage)
            {
                var grid = (IRegularGridCoverage)e.Item;

                var driverName = GdalHelper.GetDriverName(path);

                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));
                    }
                }
            }
        }
Example #19
0
        public void CreateDS(Raster.RasterDriver driver, FileInfo finfo, ExtentRectangle theExtent, Projection proj, GdalDataType theType)
        {
            List <string> creationOpts = new List <string>();

            switch (driver)
            {
            case Raster.RasterDriver.GTiff:
                creationOpts.Add("COMPRESS=LZW");
                break;

            case Raster.RasterDriver.HFA:
                creationOpts.Add("COMPRESS=PACKBITS");
                break;
            }
            Driver driverobj = Gdal.GetDriverByName(Enum.GetName(typeof(Raster.RasterDriver), driver));

            _ds = driverobj.Create(finfo.FullName, theExtent.Cols, theExtent.Rows, 1, theType._origType, creationOpts.ToArray());
            _ds.SetGeoTransform(theExtent.Transform);
            _ds.SetProjection(proj.OriginalString);

            SetNoData((double)origNodataVal);
        }
Example #20
0
        public static bool GdalTranslate(string srcPath, string dstPath, string[] options, Gdal.GDALProgressFuncDelegate callback = null)
        {
            Dataset result = null;

            using (Dataset inputDataset = Gdal.Open(srcPath, Access.GA_ReadOnly))
            {
                try
                {
                    result = Gdal.wrapper_GDALTranslate(dstPath, inputDataset, new GDALTranslateOptions(options), callback, null);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.ToString());
                    return(false);
                }
                finally
                {
                    result.Dispose();
                }
                return(true);
            }
        }
Example #21
0
        public override IRasterBand[] GetDefaultBands()
        {
            int bandNo = 0;

            using (Hdf5Operator hdf = new Hdf5Operator(_provider.fileName))
            {
                List <IRasterBand> rasterBands = new List <IRasterBand>();
                foreach (string bandname in defaultBandnames)
                {
                    Dataset       ds     = Gdal.Open(ToDatasetFullName(bandname), _access);
                    IRasterBand[] rBands = ReadBandsFromGDAL(ds, _provider);
                    rasterBands.AddRange(rBands);
                    for (int i = 0; i < rBands.Length; i++)
                    {
                        rBands[i].Description = bandname;
                        rBands[i].BandNo      = bandNo++;
                    }
                }
                rasterBands.Sort();
                return(rasterBands.Count > 0 ? rasterBands.ToArray() : null);
            }
        }
Example #22
0
        private IExtractResult GenerateExtractResult(string gfrFile, IRasterDataProvider dataPrd)
        {
            IPixelIndexMapper result   = PixelIndexMapperFactory.CreatePixelIndexMapper("FIR", dataPrd.Width, dataPrd.Height, dataPrd.CoordEnvelope, dataPrd.SpatialRef);
            Dataset           _dataset = Gdal.Open(gfrFile, Access.GA_ReadOnly);

            if (_dataset.RasterCount == 0)
            {
                return(result);
            }
            else
            {
                CoordEnvelope envelope = dataPrd.CoordEnvelope.Clone();
                double        maxX     = envelope.MaxX;
                double        minX     = envelope.MinX;
                double        maxY     = envelope.MaxY;
                double        minY     = envelope.MinY;
                using (IVectorFeatureDataReader dr = VectorDataReaderFactory.GetUniversalDataReader(gfrFile) as IVectorFeatureDataReader)
                {
                    Feature[] features = dr.FetchFeatures();
                    for (int i = 0; i < features.Length; i++)
                    {
                        double x, y;
                        if (double.TryParse(features[i].FieldValues[4], out x) && double.TryParse(features[i].FieldValues[3], out y))
                        {
                            if (IsInRange(minX, maxX, x) && IsInRange(minY, maxY, y))
                            {
                                int index = GetIndex(x, y);
                                if (index >= result.Count)
                                {
                                    break;
                                }
                                result.Put(index);
                            }
                        }
                    }
                }
                return(result);
            }
        }
Example #23
0
 /// <summary>
 /// 构建raster层
 /// </summary>
 /// <param name="rasterFilename"></param>
 public GRasterLayer(string rasterFilename)
 {
     //注册gdal库
     Gdal.AllRegister();
     //图层名
     _name = Path.GetFileNameWithoutExtension(rasterFilename);
     //只读方式读取图层
     _pDataSet = Gdal.Open(rasterFilename, Access.GA_ReadOnly);
     //波段数目
     _bandCount = _pDataSet.RasterCount;
     //读取band
     _bandCollection = new List <IGBand>();
     for (int i = 1; i <= _bandCount; i++)
     {
         Band pBand = _pDataSet.GetRasterBand(i);
         _pDataType = pBand.DataType;
         if (_pDataType == DataType.GDT_Float32 || _pDataType == DataType.GDT_Byte)
         {
             _bandCollection.Add(new GFloat32Band(pBand));
         }
     }
 }
Example #24
0
        public static int getShapeCount(string strVectorFile)
        {
            int nCount = 0;

            Gdal.AllRegister();
            // 为了支持中文路径,请添加下面这句代码
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");
            // 为了使属性表字段支持中文,请添加下面这句
            OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "");

            // 注册所有的驱动
            Ogr.RegisterAll();

            //打开数据
            DataSource ds = Ogr.Open(strVectorFile, 0);

            if (ds == null)
            {
                MessageBox.Show("打开文件【{0}】失败!", strVectorFile);
                return(nCount);
            }

            nCount = ds.GetLayerCount();
            // 获取第一个图层
            Layer oLayer = ds.GetLayerByIndex(0);

            if (oLayer == null)
            {
                MessageBox.Show("获取第{0}个图层失败!\n", "0");
                return(nCount);
            }

            // 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空
            oLayer.ResetReading();
            //FeatureDefn oDefn = oLayer.GetLayerDefn();
            int FeatureCount = oLayer.GetFeatureCount(0);

            return(FeatureCount);
        }
Example #25
0
 public static bool GdalWarp(string srcPath, string dstPath, string[] options, Gdal.GDALProgressFuncDelegate callback = null)
 {
     GdalConfiguration.ConfigureGdal();
     using (Dataset inputDataset = Gdal.Open(srcPath, Access.GA_ReadOnly))
     {
         IntPtr[] ptr      = { Dataset.getCPtr(inputDataset).Handle };
         GCHandle gcHandle = GCHandle.Alloc(ptr, GCHandleType.Pinned);
         Dataset  result   = null;
         try
         {
             SWIGTYPE_p_p_GDALDatasetShadow dss = new SWIGTYPE_p_p_GDALDatasetShadow(gcHandle.AddrOfPinnedObject(), false, null);
             result = Gdal.wrapper_GDALWarpDestName(dstPath, 1, dss, new GDALWarpAppOptions(options), callback, null);
         }
         catch (Exception) { return(false); }
         finally
         {
             gcHandle.Free();
             result.Dispose();
         }
     }
     return(true);
 }
        public void SavedCode()
        {
            using (Dataset dataset = Gdal.Open(Path, Access.GA_ReadOnly))
            {
                if (dataset == null)
                {
                    throw new Exception($"GDAL couldn't open {Path}");
                }
                Width  = dataset.RasterXSize;
                Height = dataset.RasterYSize;
                Debug.Assert(dataset.RasterCount == 1);

                dataset.GetGeoTransform(AffineTransform);
                Projection = dataset.GetProjectionRef();

                var latLonSpatialReference = new OSGeo.OSR.SpatialReference(LatLonProjection);
                var imgSpatialReference    = new OSGeo.OSR.SpatialReference(LatLonProjection);

                PixelToLatLon = new OSGeo.OSR.CoordinateTransformation(imgSpatialReference, latLonSpatialReference);
                LatLonToPixel = new OSGeo.OSR.CoordinateTransformation(latLonSpatialReference, imgSpatialReference);
            }
        }
        private static ISpatialReference TryGetSpatialRefForTilFile(string fname, out double[] GTs)
        {
            GTs = new double[6];
            string[] allLines = File.ReadAllLines(fname);
            if (allLines == null || allLines.Length == 0)
            {
                return(null);
            }
            //filename = "08MAR25030758-M2AS_R1C1-052827221030_01_P001.TIF";
            string atif = null;

            foreach (string aLine in allLines)
            {
                if (aLine.Contains("filename = \"") && aLine.EndsWith(".TIF\";"))
                {
                    atif = aLine.Replace("filename = \"", string.Empty).Replace("\";", string.Empty).Trim();
                    break;
                }
            }
            if (atif == null)
            {
                return(null);
            }
            atif = Path.Combine(Path.GetDirectoryName(fname), atif);
            if (!File.Exists(atif))
            {
                return(null);
            }
            using (Dataset ds = Gdal.Open(atif, Access.GA_ReadOnly))
            {
                ds.GetGeoTransform(GTs);
                string spatialRefString = ds.GetProjectionRef();
                if (string.IsNullOrWhiteSpace(spatialRefString))
                {
                    return(null);
                }
                return(SpatialReferenceFactory.GetSpatialReferenceByWKT(spatialRefString, enumWKTSource.GDAL));
            }
        }
Example #28
0
        public unsafe static float[,] ReadGeotiffAsFloatArray(string path, float?no_data = null)
        {
            if (!GetGdalDrivers())
            {
                return(null);
            }
            float[,] ary = null;
            using (var ds = Gdal.Open(path, Access.GA_ReadOnly))
            {
                var height = ds.RasterYSize;
                var width  = ds.RasterXSize;
                ary = new float[height, width];
                fixed(float *ary_ptr = &ary[0, 0])
                {
                    var iptr = new IntPtr(ary_ptr);
                    var band = ds.GetRasterBand(1);

                    band.GetNoDataValue(out double band_no_data, out int hasval);
                    band.ReadRaster(0, 0, width, height, iptr, width, height, DataType.GDT_Float32, 0, 0);

                    if (no_data.HasValue && hasval != 0)
                    {
                        var band_no_dataf = (float)band_no_data;
                        var no_dataf      = no_data.Value;
                        for (var row = 0; row < ary.GetLength(0); row++)
                        {
                            for (var col = 0; col < ary.GetLength(1); col++)
                            {
                                if (ary[row, col] == band_no_dataf)
                                {
                                    ary[row, col] = no_dataf;
                                }
                            }
                        }
                    }
                }
            }
            return(ary);
        }
        public static Envelope GetExtents([NotNull] Dataset dataset)
        {
            if (dataset == null) return null;
            var geoTrans = new double[6];
            dataset.GetGeoTransform(geoTrans);
            var err = (CPLErr)Gdal.GetLastErrorType();
            if (CPLErr.CE_None != err)
            {
                throw new ApplicationException("GetGeoTransform() failed.");
            }

            var regularGridGeoTransform = new RegularGridGeoTransform(geoTrans);

            return GeometryFactory.CreateEnvelope(regularGridGeoTransform.Left,
                                                  regularGridGeoTransform.Left +
                                                  (regularGridGeoTransform.HorizontalPixelResolution*
                                                   dataset.RasterXSize),
                                                  regularGridGeoTransform.Top -
                                                  (regularGridGeoTransform.VerticalPixelResolution*
                                                   dataset.RasterYSize),
                                                  regularGridGeoTransform.Top);
        }
Example #30
0
        /// <summary>
        /// Configures gdal;
        /// expects gdal stuff to come from http://www.gisinternals.com/sdk/ and maintain the folder structure
        /// created by the msi installers
        /// </summary>
        public static void ConfigureGdal()
        {
            if (GdalConfigured)
            {
                return;
            }


            // Prepend native path to environment path, to ensure the
            // right libs are being used.
            var path = Environment.GetEnvironmentVariable("PATH");

            path = GdalPath + ";" + Path.Combine(GdalPath, "gdalplugins") + ";" + path;
            Environment.SetEnvironmentVariable("PATH", path);

            // Set the additional GDAL environment variables.
            var gdalData = Path.Combine(GdalPath, "gdal-data");

            Environment.SetEnvironmentVariable("GDAL_DATA", gdalData);
            Gdal.SetConfigOption("GDAL_DATA", gdalData);

            var driverPath = Path.Combine(GdalPath, "gdalplugins");

            Environment.SetEnvironmentVariable("GDAL_DRIVER_PATH", driverPath);
            Gdal.SetConfigOption("GDAL_DRIVER_PATH", driverPath);

            Environment.SetEnvironmentVariable("GEOTIFF_CSV", gdalData);
            Gdal.SetConfigOption("GEOTIFF_CSV", gdalData);

            var projSharePath = Path.Combine(GdalPath, "projlib");

            Environment.SetEnvironmentVariable("PROJ_LIB", projSharePath);
            Gdal.SetConfigOption("PROJ_LIB", projSharePath);


            // Register drivers
            Gdal.AllRegister();
            GdalConfigured = true;
        }
Example #31
0
        public void CreateCopy()
        {
            var documents =
                System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            var dstFileName = System.IO.Path.Combine(documents, "bogota2.tif");

            if (File.Exists(dstFileName))
            {
                File.Delete(dstFileName);
            }

            var srcDS    = Gdal.Open(StartPhase.BogotaTiffPath, Access.GA_ReadOnly);
            var srcTiled = srcDS.GetMetadataItem("TILED", "IMAGE_STRUCTURE");
            var srcComp  = srcDS.GetMetadataItem("COMPRESSION", "IMAGE_STRUCTURE");

            //Assert.AreEqual (null, srcTiled);
            Assert.AreEqual(null, srcComp);

            var dstDS = driver.CreateCopy(dstFileName, srcDS, 0,
                                          new string[2] {
                "TILED=YES", "COMPRESS=PACKBITS"
            },
                                          null, null);
            var dstTiled = dstDS.GetMetadataItem("TILED", "IMAGE_STRUCTURE");
            var dstComp  = dstDS.GetMetadataItem("COMPRESSION", "IMAGE_STRUCTURE");

            //Assert.AreEqual ("YES", dstTiled);
            Assert.AreEqual("PACKBITS", dstComp);

            if (dstDS != null)
            {
                dstDS.Dispose();
                dstDS = null;
            }
            srcDS.Dispose();
            srcDS = null;

            Assert.True(File.Exists(dstFileName));
        }