Exemple #1
0
        public LogicalRasterDataProvider(string fileName, IRasterBand[] rasterBands, object tag)
        {
            if (rasterBands == null || rasterBands.Length == 0)
            {
                throw new ArgumentNullException("rasterBands");
            }
            _tag       = tag;
            _fileNames = new string[] { fileName };
            List <IRasterBand> bs = new List <IRasterBand>();
            bool isFirst          = true;

            foreach (IRasterBand band in rasterBands)
            {
                if (isFirst)
                {
                    _dataType       = band.DataType;
                    _width          = band.Width;
                    _height         = band.Height;
                    _coordEnvelope  = band.CoordEnvelope;
                    _coordType      = band.RasterDataProvider.CoordType;
                    _spatialRef     = band.SpatialRef;
                    _coordTransform = band.CoordTransform;
                    isFirst         = false;
                }
                else
                {
                    if (_dataType != band.DataType ||
                        _width != band.Width ||
                        _height != band.Height)
                    {
                        continue;
                    }
                    if (_coordType != null && _coordType != band.RasterDataProvider.CoordType)
                    {
                        continue;
                    }
                    if (_coordEnvelope != null && !CoordEnvelopeEquals(_coordEnvelope, band.CoordEnvelope))
                    {
                        continue;
                    }
                    if (_spatialRef != null && !_spatialRef.IsSame(band.SpatialRef))
                    {
                        continue;
                    }
                }
                bs.Add(band);
            }
            _rasterBands.AddRange(bs);
        }
Exemple #2
0
 public void Transform(ISpatialReference srcSpatialRef, double[] srcXs, double[] srcYs, ISpatialReference dstSpatialRef)
 {
     using (IProjectionTransform transform = ProjectionTransformFactory.GetProjectionTransform(srcSpatialRef, dstSpatialRef))
     {
         if (!srcSpatialRef.IsSame(dstSpatialRef))
         {
             transform.Transform(srcXs, srcYs);
         }
     }
 }
Exemple #3
0
        //private void button4_Click(object sender, EventArgs e)
        //{
        //    ISpatialReference srcSpatialRef = SpatialReferenceFactory.GetSpatialReferenceByPrjFile("WGS 1984.prj");
        //    srcSpatialRef = SpatialReferenceFactory.GetSpatialReferenceByPrjFile("Mercator (sphere).prj");
        //    string proj4 = srcSpatialRef.ToProj4String();
        //    srcSpatialRef = SpatialReferenceFactory.GetSpatialReferenceByProj4String(proj4);
        //}

        //private void button4_Click(object sender, EventArgs e)
        //{
        //    TestFy3AVirrProjection fyp = new TestFy3AVirrProjection();
        //    Action<int, string> progressCallback = new Action<int, string>(OutProgress);
        //    fyp.DataReady(progressCallback);
        //    Stopwatch stopwatch = new Stopwatch();
        //    stopwatch.Start();
        //    fyp.TestFy3VIRR();
        //    stopwatch.Stop();
        //    WriteLine("数据投影{0}ms", stopwatch.ElapsedMilliseconds);
        //    stopwatch.Restart();
        //}

        private void TestPrj4Parser_Click(object sender, EventArgs e)
        {
            ISpatialReference srcSpatialRef = null;// SpatialReferenceFactory.GetSpatialReferenceByPrjFile("WGS 1984.prj");
            string            prjFile       = "f:\\32600.prj";

            srcSpatialRef = SpatialReferenceFactory.GetSpatialReferenceByPrjFile("Mercator (sphere).prj");
            string            proj4           = srcSpatialRef.ToProj4String();
            ISpatialReference inverSpatialRef = SpatialReferenceFactory.GetSpatialReferenceByProj4String(proj4);

            bool isSame = srcSpatialRef.IsSame(inverSpatialRef);
        }
        /// <summary>
        /// Assignes selected projection and displays results
        /// </summary>
        public bool Assign(string filename, ISpatialReference proj)
        {
            var projWgs84 = new SpatialReference();

            if (!projWgs84.ImportFromEpsg(4326))
            {
                MessageService.Current.Warn("Failed to initialize WGS84 coordinate system.");
                return(false);
            }

            bool sameProj = proj.IsSame(projWgs84);
            int  count    = 0;

            bool success  = false;
            int  rowIndex = dgv.Rows.Add();

            _shapefile = new FeatureSet(filename);

            Text = @"Assigning projection: " + Path.GetFileName(filename);
            lblProjection.Text = @"Projection: " + proj.Name;

            // it will be faster to assing new instance of class
            // as ImportFromEPSG() is slow according to GDAL documentation
            _shapefile.Projection.CopyFrom(proj);

            if (!sameProj)
            {
                // we can't show preview on map without reprojection
                if ((_shapefile.StartEditingShapes()))
                {
                    if (_shapefile.ReprojectInPlace(projWgs84, ref count))
                    {
                        success = true;
                    }
                }
            }
            else
            {
                success = true;
            }

            if (success)
            {
                AddShapefile(_shapefile);
                return(true);
            }

            // no success in reprojection
            _shapefile.Close();
            return(false);
        }
 private void btnModify_Click(object sender, EventArgs e)
 {
     if (_spatialReference == null)
     {
         return;
     }
     _preSpatialReference = _spatialReference;
     if (_spatialReference.ProjectionCoordSystem == null)
     {
         GeoCoordinateDefine geoCoordinateDefine = new GeoCoordinateDefine(_spatialReference, enumControlType.Modify);
         geoCoordinateDefine.Text = "地理坐标系属性";
         TryApplyGeo(geoCoordinateDefine);
         if (geoCoordinateDefine.DialogResult == System.Windows.Forms.DialogResult.OK)
         {
             //IsSame()函数中没有对名字进行比较
             if (!_spatialReference.IsSame(_preSpatialReference) ||
                 (_spatialReference.GeographicsCoordSystem.Name != _preSpatialReference.GeographicsCoordSystem.Name))
             {
                 NeedSaveToFile();
             }
         }
     }
     else
     {
         PrjCoordinateDefine prjCoordinateDefine = new PrjCoordinateDefine(_spatialReference, enumControlType.Modify);
         prjCoordinateDefine.Text = "投影坐标系属性";
         TryApplyPrj(prjCoordinateDefine);
         if (prjCoordinateDefine.DialogResult == System.Windows.Forms.DialogResult.OK)
         {
             if (!_spatialReference.IsSame(_preSpatialReference) ||
                 (_spatialReference.GeographicsCoordSystem.Name != _preSpatialReference.GeographicsCoordSystem.Name) ||
                 (_spatialReference.Name != _preSpatialReference.Name))
             {
                 NeedSaveToFile();
             }
         }
     }
 }
Exemple #6
0
        private void CreateOverviewBmp(ISpatialReference spatialRef, int[] bandNos)
        {
            if (spatialRef == null)
            {
                spatialRef = SpatialReference.GetDefault();
            }
            if (_spatialRef == null || !_spatialRef.IsSame(spatialRef))
            {
                _spatialRef = spatialRef;
            }
            Bitmap bmp;

            GetOverview(MainFile, _spatialRef, bandNos, out bmp, out _errorMsg);
            OverViewBmp = bmp;
        }
        private void button18_Click(object sender, EventArgs e)
        {
            string wkt = "GEOGCS[\"等经纬度投影\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]]";

            wkt = "PROJCS[\"Hammer投影\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Hammer-Aitoff (world)\"]PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],PARAMETER[\"central_meridian\",105],UNIT[\"Meter\",1]]";
            ISpatialReference srcSpatialRef   = SpatialReferenceFactory.GetSpatialReferenceByWKT(wkt, enumWKTSource.EsriPrjFile);
            string            proj4           = srcSpatialRef.ToProj4String();
            ISpatialReference inverSpatialRef = SpatialReferenceFactory.GetSpatialReferenceByProj4String(proj4);

            inverSpatialRef.IsSame(srcSpatialRef);

            IProjectionTransform tr = ProjectionTransformFactory.GetProjectionTransform(srcSpatialRef, SpatialReference.GetDefault());

            double[] x = new double[] { 1534910 };
            double[] y = new double[] { 4255978 };
            x = new double[] { 121.913 };
            y = new double[] { 38.957 };
            tr.InverTransform(x, y);
            tr.Transform(x, y);
        }
Exemple #8
0
        public static bool IsDialectOf(this IProjectionDatabase projectionDatabase, ISpatialReference multiDefinedProj, ISpatialReference testProj)
        {
            if (multiDefinedProj.IsEmpty)
            {
                return(false);
            }

            var db = projectionDatabase;

            if (db == null)
            {
                return(false);
            }

            var cs = db.GetCoordinateSystem(multiDefinedProj, ProjectionSearchType.Enhanced);

            if (cs == null)
            {
                return(false);
            }

            db.ReadDialects(cs);

            foreach (var dialect in cs.Dialects)
            {
                var projTemp = new SpatialReference();
                if (!projTemp.ImportFromAutoDetect(dialect))
                {
                    continue;
                }

                if (testProj.IsSame(projTemp))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #9
0
 /// <summary>
 /// 根据给出的经纬度数据集或者投影坐标数据集,计算其是否在指定的范围内,并且计算出有效率,以及实际输出范围
 /// </summary>
 /// <param name="xs"></param>
 /// <param name="ys"></param>
 /// <param name="validEnv"></param>
 /// <param name="oSpatialRef"></param>
 /// <param name="tSpatialRef"></param>
 /// <param name="validRate"></param>
 /// <param name="outEnv"></param>
 /// <returns></returns>
 public bool VaildEnvelope(double[] xs, double[] ys, PrjEnvelope validEnv, ISpatialReference oSpatialRef, ISpatialReference tSpatialRef, out double validRate, out PrjEnvelope outEnv)
 {
     if (validEnv == null || validEnv.IsEmpty)
     {
         throw new ArgumentNullException("validEnv", "参数[有效范围]不能为空");
     }
     if (tSpatialRef == null)
     {
         tSpatialRef = SpatialReference.GetDefault();
     }
     if (oSpatialRef == null)
     {
         oSpatialRef = SpatialReference.GetDefault();
     }
     using (IProjectionTransform transform = ProjectionTransformFactory.GetProjectionTransform(oSpatialRef, tSpatialRef))
     {
         if (!oSpatialRef.IsSame(tSpatialRef))
         {
             transform.Transform(xs, ys);
         }
         bool isLatLong = (tSpatialRef.ProjectionCoordSystem == null && tSpatialRef.GeographicsCoordSystem != null);
         return(PrjEnvelope.HasValidEnvelope(xs, ys, validEnv, out validRate, out outEnv));
     }
 }
Exemple #10
0
        private static void ConvertHdf4To5(Hdf4FileAttrs hdf4FileAttrs, string f5name,
                                           Action <string, int, int> messageAction, SEnvelope outenvelope, float dstResolution,
                                           ISpatialReference dstSpatialReference)
        {
            try
            {
                // Create a new file using H5F_ACC_TRUNC access,
                // default file creation properties, and default file
                // access properties.
                H5FileId fileId = H5F.create(f5name, H5F.CreateMode.ACC_TRUNC);

                int nxf5 = hdf4FileAttrs.Hdf4FileAttr.XDim;
                int nyf5 = hdf4FileAttrs.Hdf4FileAttr.YDim;
                int rank = 2;

                //测试读取的科学数据集及其属性
                int sdscount = hdf4FileAttrs.Hdf4FileAttr.DataFields.Count;

                SEnvelope envelopeNew = null;
                UInt16[]  rows        = null; //正向查找表
                UInt16[]  cols        = null; //正向查找表
                Size      srcStepSize = Size.Empty;
                Size      outSize     = Size.Empty;
                try
                {
                    for (int k = 0; k < sdscount; k++)
                    {
                        ConvertHdf4To5BySds(hdf4FileAttrs, messageAction, k, nyf5, nxf5, rank, fileId, outenvelope, dstResolution, dstSpatialReference, ref rows, ref cols, ref srcStepSize, ref outSize);
                        if (envelopeNew == null && dstSpatialReference != null && outenvelope != null)
                        {
                            envelopeNew = outenvelope;
                        }
                    }
                    if (envelopeNew != null)
                    {
                        hdf4FileAttrs.RefreshPointString(envelopeNew);
                    }
                }
                finally
                {
                    rows        = null;
                    cols        = null;
                    srcStepSize = Size.Empty;
                    GC.Collect();
                }

                HDFAttributeDef[]      attributeDef5s  = hdf4FileAttrs.GetHDFAttributeDefs();
                List <HDFAttributeDef> updateFileAttrs = new List <HDFAttributeDef>();
                updateFileAttrs.AddRange(attributeDef5s);
                if (dstSpatialReference != null && dstSpatialReference.IsSame(SpatialReference.GetDefault()))
                {
                    //投影信息
                    string          projtype    = "Geopraphic Latitude longtitude";
                    HDFAttributeDef projecttype = new HDFAttributeDef("Projection Type", typeof(string), projtype.Length, projtype);
                    updateFileAttrs.Add(projecttype);
                    //写四角坐标信息
                    HDFAttributeDef lefttopY = new HDFAttributeDef("Left-Top Latitude", typeof(float), 1, new float[] { (float)outenvelope.YMax });
                    updateFileAttrs.Add(lefttopY);
                    HDFAttributeDef lefttopX = new HDFAttributeDef("Left-Top Longtitude", typeof(float), 1, new float[] { (float)outenvelope.XMin });
                    updateFileAttrs.Add(lefttopX);
                    HDFAttributeDef boottomrightY = new HDFAttributeDef("Bottom-Right Latitude", typeof(float), 1, new float[] { (float)outenvelope.YMin });
                    updateFileAttrs.Add(boottomrightY);
                    HDFAttributeDef boottomrightX = new HDFAttributeDef("Bottom-Right Longtitude", typeof(float), 1, new float[] { (float)outenvelope.XMax });
                    updateFileAttrs.Add(boottomrightX);
                    HDFAttributeDef xResolution = new HDFAttributeDef("Longtitude Resolution", typeof(float), 1, new float[] { (float)dstResolution });
                    updateFileAttrs.Add(xResolution);
                    HDFAttributeDef yResolution = new HDFAttributeDef("Latitude Resolution", typeof(float), 1, new float[] { (float)dstResolution });
                    updateFileAttrs.Add(yResolution);
                }
                foreach (HDFAttributeDef attributeDef5 in updateFileAttrs)
                {
                    WriteHdfAttributes.WriteHdfAttribute(fileId, attributeDef5);
                }

                H5F.close(fileId);
            }
            catch (Exception ex)
            {
                throw new Exception("拼接Hdf4时出错,具体信息:" + ex.Message, ex);
            }
        }
Exemple #11
0
        private static void ConvertHdf4To5BySds <T>(Hdf4FileAttrs hdf4FileAttrs, int nyf5, int nxf5, int k, int rank,
                                                    H5FileId fileId, string sdName, HDF4Helper.DataTypeDefinitions dtaDefinitions, Action <string, int, int> messageAction,
                                                    SEnvelope envelopeNew, T fillValue, float dstResolution, ISpatialReference dstSpatialReference, ref UInt16[] rows, ref UInt16[] cols, ref Size srcStepSize, ref Size outSize)
        {
            T[,] data = new T[nyf5, nxf5];
            H5DataSetId dsetId = null;

            T[,] dataNew = null;
            SDataByProject <T> dataByProject = null;

            try
            {
                for (int i = 0; i < hdf4FileAttrs.Count; i++)
                {
                    Hdf4FileAttr hdf4FileAttr = hdf4FileAttrs[i];
                    if (messageAction != null)
                    {
                        messageAction(String.Format("正在转换数据集 {0}", sdName), k, i);
                    }
                    H4SDS sd = hdf4FileAttr.H4File.Datasets[k];
                    GetDataByHdf4(sd, rank, hdf4FileAttr, data);
                }

                dataNew = data;
                if (outSize.IsEmpty)
                {
                    outSize = new Size(nxf5, nyf5);
                }
                if (dstSpatialReference != null && dstSpatialReference.IsSame(SpatialReference.GetDefault()))
                {
                    if (rows == null && cols == null)
                    {
                        PrjEnvelope     srcEnvelope = new PrjEnvelope(hdf4FileAttrs.Hdf4FileAttr.Envelope.XMin, hdf4FileAttrs.Hdf4FileAttr.Envelope.XMax, hdf4FileAttrs.Hdf4FileAttr.Envelope.YMin, hdf4FileAttrs.Hdf4FileAttr.Envelope.YMax);
                        PrjEnvelope     outenvelpoe = new PrjEnvelope(envelopeNew.XMin, envelopeNew.XMax, envelopeNew.YMin, envelopeNew.YMax);
                        FilePrjSettings prjSetting  = new FilePrjSettings();
                        prjSetting.OutEnvelope    = outenvelpoe;
                        prjSetting.OutResolutionX = dstResolution;
                        prjSetting.OutResolutionY = dstResolution;
                        outSize = prjSetting.OutSize;
                        Size  inSize         = new Size(hdf4FileAttrs.Hdf4FileAttr.XDim, hdf4FileAttrs.Hdf4FileAttr.YDim);
                        float dstResoultion  = dstResolution;
                        float srcResoultionX = (float)(hdf4FileAttrs.Hdf4FileAttr.CellWidth);
                        float srcResoultionY = (float)(hdf4FileAttrs.Hdf4FileAttr.CellHeight);
                        dataByProject = GetDataByProject <T>(dataNew, srcEnvelope, outenvelpoe, inSize, outSize, dstResoultion, srcResoultionX, srcResoultionY, fillValue, dstSpatialReference, out rows, out cols, out srcStepSize);
                    }
                    else
                    {
                        T[,] dstData  = new T[outSize.Height, outSize.Width];
                        dataByProject = DoProject <T>(dataNew, fillValue, ref outSize, ref srcStepSize, dstData, rows, cols);
                    }
                    if (dataByProject != null)
                    {
                        dataNew = dataByProject.Data;
                    }
                }

                long[] dims = new long[rank];
                dims[0] = Convert.ToInt64(outSize.Height);
                dims[1] = Convert.ToInt64(outSize.Width);
                H5DataSpaceId dspaceId = H5S.create_simple(rank, dims);
                H5T.H5Type    h5Type   = Utility.GetH5Type(dtaDefinitions);
                // Define datatype for the data in the file.
                H5DataTypeId dtypeId = H5T.copy(h5Type);

                // Create the data set DATASETNAME.
                dsetId = H5D.create(fileId, sdName, dtypeId, dspaceId);
                // Write the one-dimensional data set array
                H5D.write(dsetId, new H5DataTypeId(h5Type), new H5Array <T>(dataNew));//H5A

                HDFAttributeDef[] attributeDef5s = hdf4FileAttrs[0].DatasetsAttributeDefs[k];
                foreach (HDFAttributeDef attributeDef5 in attributeDef5s)
                {
                    WriteHdfAttributes.WriteHdfAttribute(dsetId, attributeDef5);
                }
            }
            finally
            {
                // Close dataset and file.
                if (dsetId != null)
                {
                    H5D.close(dsetId);
                }
                if (data != null)
                {
                    data = null;
                }
                if (dataNew != null)
                {
                    dataNew = null;
                }
                GC.Collect();
            }
        }
Exemple #12
0
        /// <summary>
        /// Does the reprojection work
        /// </summary>
        private void DoReprojection(IEnumerable <string> filenames, ISpatialReference projection, bool inPlace)
        {
            var report = new TesterReportForm();

            report.InitProgress(projection);
            var files = new List <string>();

            int count = 0; // number of successfully reprojected shapefiles

            foreach (string filename in filenames)
            {
                var layer = GeoSource.Open(filename) as ILayerSource;
                if (layer == null)
                {
                    continue;
                }

                ILayerSource layerNew = null;

                if (projection.IsSame(layer.Projection))
                {
                    report.AddFile(layer.Filename, projection.Name, ProjectionOperaion.SameProjection, "");
                    files.Add(layer.Filename);
                }
                else
                {
                    TestingResult result = _reprojectingService.Reproject(layer, out layerNew, projection, report);
                    if (result == TestingResult.Ok || result == TestingResult.Substituted)
                    {
                        var oper = result == TestingResult.Ok
                                       ? ProjectionOperaion.Reprojected
                                       : ProjectionOperaion.Substituted;
                        string newName = layerNew == null ? "" : layerNew.Filename;
                        report.AddFile(layer.Filename, layer.Projection.Name, oper, newName);
                        files.Add(newName == "" ? layer.Filename : newName);
                        count++;
                    }
                    else
                    {
                        var operation = result == TestingResult.Error
                                            ? ProjectionOperaion.FailedToReproject
                                            : ProjectionOperaion.Skipped;
                        report.AddFile(layer.Filename, layer.Projection.Name, ProjectionOperaion.Skipped, "");
                    }
                }

                layer.Close();
                if (layerNew != null)
                {
                    layerNew.Close();
                }
            }
            report.ShowReport(projection, "Reprojection results:", ReportType.Loading);

            IEnumerable <string> names = _context.Layers.Select(l => l.Filename).ToList();

            names = files.Except(names);

            if (count == 0)
            {
                MessageService.Current.Info("No files to add to the map.");
                return;
            }

            if (!projection.IsSame(_context.Map.Projection))
            {
                MessageService.Current.Info(
                    "Chosen projection is different from the project one. The layers can't be added to map.");
                return;
            }

            if (!names.Any())
            {
                MessageService.Current.Info("No files to add to the map.");
                return;
            }

            if (MessageService.Current.Ask("Do you want to add layers to the project?"))
            {
                //_context.Layers.StartAddingSession();

                foreach (string filename in names)
                {
                    var ds    = GeoSource.Open(filename);
                    var layer = LayerSourceHelper.ConvertToLayer(ds);
                    _context.Layers.Add(layer);
                }

                //_context.Layers.StopAddingSession();
            }
        }