Beispiel #1
0
        /// <summary>
        /// Runs GdalWarp with passed parameters.
        /// </summary>
        /// <param name="inputFileInfo">Input GeoTiff file.</param>
        /// <param name="outputFileInfo">Output file.</param>
        /// <param name="options">Array of string parameters.</param>
        /// <param name="callback">Delegate for progress reporting from Gdal.</param>
        /// <returns></returns>
        public static async ValueTask Warp(FileInfo inputFileInfo, FileInfo outputFileInfo, string[] options,
                                           OSGeo.GDAL.Gdal.GDALProgressFuncDelegate callback = null)
        {
            #region Parameters checking

            CheckHelper.CheckFile(inputFileInfo, true);
            CheckHelper.CheckFile(outputFileInfo, false);
            CheckHelper.CheckDirectory(outputFileInfo.Directory);

            #endregion

            //Initialize Gdal, if needed.
            ConfigureGdal();

            await Task.Run(() =>
            {
                using (Dataset inputDataset = OSGeo.GDAL.Gdal.Open(inputFileInfo.FullName, Access.GA_ReadOnly))
                {
                    GCHandle gcHandle = GCHandle.Alloc(new[] { Dataset.getCPtr(inputDataset).Handle },
                                                       GCHandleType.Pinned);
                    SWIGTYPE_p_p_GDALDatasetShadow gdalDatasetShadow =
                        new SWIGTYPE_p_p_GDALDatasetShadow(gcHandle.AddrOfPinnedObject(), false, null);

                    // ReSharper disable once UnusedVariable
                    using (Dataset resultDataset =
                               OSGeo.GDAL.Gdal.wrapper_GDALWarpDestName(outputFileInfo.FullName, 1, gdalDatasetShadow,
                                                                        new GDALWarpAppOptions(options), callback,
                                                                        string.Empty)) { gcHandle.Free(); }
                }
            }).ConfigureAwait(false);

            //Was file created?
            CheckHelper.CheckFile(outputFileInfo, true);
        }
Beispiel #2
0
        /// <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);

                GCHandle gcHandle = GCHandle.Alloc(new[] { Dataset.getCPtr(inputDataset).Handle },
                                                   GCHandleType.Pinned);
                SWIGTYPE_p_p_GDALDatasetShadow gdalDatasetShadow =
                    new SWIGTYPE_p_p_GDALDatasetShadow(gcHandle.AddrOfPinnedObject(), false, null);

                // We need to create variable in order to correctly dispose result dataset,
                // it's gdal's bindings issue
                // ReSharper disable once UnusedVariable
                using Dataset resultDataset =
                          Gdal.wrapper_GDALWarpDestName(outputFilePath, 1, gdalDatasetShadow,
                                                        new GDALWarpAppOptions(options), callback, string.Empty);

                gcHandle.Free();
            }));
        }
Beispiel #3
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);
 }
Beispiel #4
0
 public static bool Warp(
     string inputFile, string outputFile, string[] options)
 {
     using (Dataset inputds = Gdal.Open(
                inputFile, Access.GA_ReadOnly))
     {
         if (inputds == null)
         {
             return(false);
         }
         IntPtr[] ptr      = { Dataset.getCPtr(inputds).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(
                 outputFile, 1, dss,
                 new GDALWarpAppOptions(options), null, null);
             if (result == null)
             {
                 throw new Exception("GdalWarp failed: " +
                                     Gdal.GetLastErrorMsg());
             }
         }
         catch (Exception) { return(false); }
         finally
         {
             gcHandle.Free();
             result.Dispose();
         }
     }
     return(true);
 }
Beispiel #5
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string datasourceFileLocation = string.Empty;

            DA.GetData <string>(0, ref datasourceFileLocation);

            string dstFileLocation = string.Empty;

            DA.GetData <string>(1, ref dstFileLocation);

            string options = string.Empty;

            DA.GetData <string>(2, ref options);

            var re = new System.Text.RegularExpressions.Regex("(?<=\")[^\"]*(?=\")|[^\" ]+");

            string[] translateOptions = re.Matches(options).Cast <Match>().Select(m => m.Value).ToArray();

            string datasourceInfo = string.Empty;
            string dstInfo        = string.Empty;
            string dstOutput      = string.Empty;


            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Look for more information about options at:");
            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "https://gdal.org/programs/gdal_polygonize.html");

            if (!string.IsNullOrEmpty(datasourceFileLocation))
            {
                using (Dataset datasource = Gdal.Open(datasourceFileLocation, Access.GA_ReadOnly))
                {
                    if (datasource == null)
                    {
                        throw new Exception("Can't open GDAL dataset: " + datasourceFileLocation);
                    }

                    SpatialReference sr = new SpatialReference(datasource.GetProjection());

                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP   = new SpatialReference(datasource.GetGCPProjection());
                    string           projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  " +
                                          "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        //sr.SetWellKnownGeogCS("WGS84");
                    }

                    ///Get info about image
                    List <string> infoOptions = new List <string> {
                        "-stats"
                    };
                    datasourceInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));

                    if (!string.IsNullOrEmpty(dstFileLocation))
                    {
                        if (string.IsNullOrEmpty(options) && File.Exists(dstFileLocation))
                        {
                            Dataset dst = Gdal.Open(dstFileLocation, Access.GA_ReadOnly);
                            dstInfo = Gdal.GDALInfo(dst, null);
                            dst.Dispose();
                            dstOutput = dstFileLocation;
                        }
                        else
                        {
                            ///https://github.com/OSGeo/gdal/issues/813
                            ///https://lists.osgeo.org/pipermail/gdal-dev/2017-February/046046.html
                            ///Odd way to go about setting source dataset in parameters for Warp is a known issue

                            var ptr      = new[] { Dataset.getCPtr(datasource).Handle };
                            var gcHandle = GCHandle.Alloc(ptr, GCHandleType.Pinned);
                            try
                            {
                                var     dss = new SWIGTYPE_p_p_GDALDatasetShadow(gcHandle.AddrOfPinnedObject(), false, null);
                                Dataset dst = Gdal.wrapper_GDALWarpDestName(dstFileLocation, 1, dss, new GDALWarpAppOptions(translateOptions), null, null);
                                if (dst == null)
                                {
                                    throw new Exception("GdalWarp failed: " + Gdal.GetLastErrorMsg());
                                }

                                dstInfo = Gdal.GDALInfo(dst, new GDALInfoOptions(infoOptions.ToArray()));
                                dst.Dispose();
                                dstOutput = dstFileLocation;
                            }
                            finally
                            {
                                if (gcHandle.IsAllocated)
                                {
                                    gcHandle.Free();
                                }
                            }
                        }
                    }
                    datasource.Dispose();
                }
            }

            DA.SetData(0, datasourceInfo);
            DA.SetData(1, dstInfo);
            DA.SetData(2, dstOutput);
        }
Beispiel #6
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string srcFileLocation = string.Empty;

            DA.GetData <string>(0, ref srcFileLocation);

            string dstFileLocation = string.Empty;

            DA.GetData <string>(1, ref dstFileLocation);

            string options = string.Empty;

            DA.GetData <string>(2, ref options);

            string[] translateOptions = options.Split(' ');

            string srcInfo   = string.Empty;
            string dstInfo   = string.Empty;
            string dstOutput = string.Empty;


            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Look for more information about options at:");
            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "https://gdal.org/programs/gdalwarp.html");

            if (!string.IsNullOrEmpty(srcFileLocation))
            {
                using (Dataset src = Gdal.Open(srcFileLocation, Access.GA_ReadOnly))
                {
                    if (src == null)
                    {
                        throw new Exception("Can't open GDAL dataset: " + srcFileLocation);
                    }

                    srcInfo = Gdal.GDALInfo(src, null);

                    if (!string.IsNullOrEmpty(dstFileLocation))
                    {
                        if (string.IsNullOrEmpty(options) && File.Exists(dstFileLocation))
                        {
                            Dataset dst = Gdal.Open(dstFileLocation, Access.GA_ReadOnly);
                            dstInfo = Gdal.GDALInfo(dst, null);
                            dst.Dispose();
                            dstOutput = dstFileLocation;
                        }
                        else
                        {
                            ///https://github.com/OSGeo/gdal/issues/813
                            ///https://lists.osgeo.org/pipermail/gdal-dev/2017-February/046046.html
                            ///Odd way to go about setting source dataset in parameters for Warp is a known issue

                            var ptr      = new[] { Dataset.getCPtr(src).Handle };
                            var gcHandle = GCHandle.Alloc(ptr, GCHandleType.Pinned);
                            try
                            {
                                var     dss = new SWIGTYPE_p_p_GDALDatasetShadow(gcHandle.AddrOfPinnedObject(), false, null);
                                Dataset dst = Gdal.wrapper_GDALWarpDestName(dstFileLocation, 1, dss, new GDALWarpAppOptions(translateOptions), null, null);
                                if (dst == null)
                                {
                                    throw new Exception("GdalWarp failed: " + Gdal.GetLastErrorMsg());
                                }

                                dstInfo = Gdal.GDALInfo(dst, null);
                                dst.Dispose();
                                dstOutput = dstFileLocation;
                            }
                            finally
                            {
                                if (gcHandle.IsAllocated)
                                {
                                    gcHandle.Free();
                                }
                            }
                        }
                    }
                    src.Dispose();
                }
            }

            DA.SetData(0, srcInfo);
            DA.SetData(1, dstInfo);
            DA.SetData(2, dstOutput);
        }