public bool LatLon_TiffToUTM_Tiff(string inPut, string outPut, int band = 1)
        {
            FileInfo inPutFile = new FileInfo(inPut);

            //입력 파일이 없다면 종료
            if (!inPutFile.Exists)
            {
                return(false);
            }
            else
            {
                //입력 파일이 tif / tiff 파일이 아니라면 종료
                if (inPutFile.Extension != ".tif" && inPutFile.Extension != ".tiff")
                {
                    return(false);
                }
            }

            #region Create Tiff
            Gdal.AllRegister();
            Dataset dataset = Gdal.Open(inPut, Access.GA_ReadOnly);

            //SpatialReference dstt_srs = new SpatialReference("");
            //dstt_srs.SetFromUserInput("+proj=utm +zone=21 +ellps=WGS84 +datum=WGS84 +units=m +no_defs");
            string t_srs_wkt = "GEOGCS[\"WGS84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS84\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.01745329251994328]]";
            //dstt_srs.ExportToWkt(out t_srs_wkt);
            //SpatialReference src_srs = new SpatialReference("");
            //src_srs.SetFromUserInput("+proj=longlat");
            string s_srs_wkt = dataset.GetProjectionRef();
            //src_srs.ExportToWkt(out s_srs_wkt);

            Dataset dswarp = Gdal.AutoCreateWarpedVRT(dataset, s_srs_wkt, t_srs_wkt, ResampleAlg.GRA_NearestNeighbour, 0.125);


            string[]          options = null;
            OSGeo.GDAL.Driver srcDrv  = Gdal.GetDriverByName("GTiff");
            Dataset           dstDs   = srcDrv.CreateCopy(outPut, dswarp, 0, options, null, null);

            //dstDs.SetProjection(dataset.GetProjection());

            //double[] geot = new double[6];
            //dataset.GetGeoTransform(geot);
            //dstDs.SetGeoTransform(geot);

            dstDs.FlushCache();
            dstDs.Dispose();
            srcDrv.Dispose();


            #endregion

            return(true);
        }
        /// <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 #3
0
        /// <summary>
        /// Use well known GeogCS such as : "EPSG:4326"
        /// </summary>
        /// <param name="sWellKnownGeogCS"></param>
        public void Warp(string sWellKnownGeogCS)
        {
            if (_ds == null)
            {
                string sMsg = string.Format("{0}/{1}: Not initialize Dataset", this.ToString(), "Warp");
                throw (new Exception(sMsg));
            }

            string           dst_wkt;
            SpatialReference oSR = new SpatialReference("");

            oSR.SetWellKnownGeogCS(sWellKnownGeogCS);
            oSR.ExportToWkt(out dst_wkt);

            string src_wkt = _ds.GetProjection();

            // The VRT driver is a format driver for GDAL that allows a virtual GDAL dataset to be composed from other GDAL datasets with repositioning, and algorithms potentially applied as well as various kinds of metadata altered or added. VRT descriptions of datasets can be saved in an XML format normally given the extension .vrt.

            // 'NearestNeighbour', 'Bilinear', 'Cubic', or 'CubicSpline'
            Dataset dsWarp = Gdal.AutoCreateWarpedVRT(_ds, src_wkt, dst_wkt, ResampleAlg.GRA_NearestNeighbour, 0);

            UpdateDataset(dsWarp);
        }
Example #4
0
        public void ProjectAndTile(RasterInfo originFile, int zoomLevel, IProgress <Status> progress)
        {
            var status = new Status
            {
                Total   = SupportedProjections.Length,
                Current = 0
            };

            foreach (var projection in SupportedProjections)
            {
                Size fullMapSize = projection.FullMapSizeFor(zoomLevel);
                var  tilesWide   = fullMapSize.Width / projection.TileSize.Width;
                var  tilesTall   = fullMapSize.Height / projection.TileSize.Height;

                status.Current++;
                status.Total  += tilesWide * tilesTall;
                status.Message = $"Projecting {projection.Name} at Zoom Level {zoomLevel}";
                progress?.Report(status);

                string baseDir = Path.Combine(projection.GetType().Name, $"{zoomLevel}");
                if (!Directory.Exists(baseDir))
                {
                    Directory.CreateDirectory(baseDir);
                }

                using (var source = Gdal.OpenShared(originFile.FullPath, Access.GA_ReadOnly))
                    using (var destination = Gdal.AutoCreateWarpedVRT(source, source.GetProjection(), projection.Wkt,
                                                                      ResampleAlg.GRA_NearestNeighbour, .0125))
                    {
                        var sourceInfo = DetermineRenderInformation(destination);

                        var ratioX = destination.RasterXSize / fullMapSize.Width;
                        var ratioY = destination.RasterYSize / fullMapSize.Height;

                        var destWidth    = (int)projection.TileSize.Width;
                        var destHeight   = (int)projection.TileSize.Height;
                        var sourceWidth  = (int)(destWidth * ratioX);
                        var sourceHeight = (int)(destHeight * ratioY);

                        var buffer = new byte[destWidth * destHeight * sourceInfo.ChannelCount];
                        var stride = destWidth * sourceInfo.ChannelCount;

                        for (int row = 0; row < tilesWide; row++)
                        {
                            for (int column = 0; column < tilesTall; column++)
                            {
                                int x = column * sourceWidth;
                                int y = row * sourceHeight;
                                destination.ReadRaster(x, y, sourceWidth, sourceHeight, buffer, destWidth,
                                                       destHeight, sourceInfo.ChannelCount, sourceInfo.BandMap, sourceInfo.PixelSpace, stride, 1);

                                var bitmap = BitmapSource.Create(destWidth, destHeight, 96, 96, sourceInfo.PixelFormat,
                                                                 sourceInfo.Colors, buffer, stride);

                                using (var stream = File.Create(Path.Combine(baseDir, $"{row}-{column}.png")))
                                {
                                    var encoder = new PngBitmapEncoder();
                                    encoder.Frames.Add(BitmapFrame.Create(bitmap));
                                    encoder.Save(stream);
                                }

                                status.Current++;
                                progress?.Report(status);
                            }
                        }
                    }
            }

            status.Current = status.Total;
            status.Message = string.Empty;
            progress?.Report(status);
        }
        public bool TiffToKml(string inPut, string outPut, int band = 1)
        {
            FileInfo inPutFile = new FileInfo(inPut);
            bool     isExtif   = false;
            bool     isExtiff  = false;

            //입력 파일이 없다면 종료
            if (!inPutFile.Exists)
            {
                return(false);
            }
            else
            {
                //입력 파일이 tif / tiff 파일이 아니라면 종료
                if (inPutFile.Extension != ".tif" && inPutFile.Extension != ".tiff")
                {
                    return(false);
                }

                if (inPutFile.Extension == ".tif")
                {
                    isExtif = true;
                }

                if (inPutFile.Extension == ".tiff")
                {
                    isExtiff = true;
                }
            }

            Gdal.AllRegister();

            try
            {
                #region Get Coordinate
                double north = 36.16465526448886; //북
                double south = 35.97362616042732; //남
                double east  = 127.5672085281825; //동
                double west  = 127.3435070025512; //서

                Dataset dataset = Gdal.Open(inPut, Access.GA_ReadOnly);

                string t_srs_wkt = "GEOGCS[\"WGS84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS84\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.01745329251994328]]";
                string s_srs_wkt = dataset.GetProjectionRef();

                Dataset dswarp = Gdal.AutoCreateWarpedVRT(dataset, s_srs_wkt, t_srs_wkt, ResampleAlg.GRA_NearestNeighbour, 0.125);


                string[]          options = null;
                OSGeo.GDAL.Driver srcDrv  = Gdal.GetDriverByName("GTiff");

                FileInfo outPutFile = new FileInfo(outPut);
                string   testPath   = string.Empty;
                if (isExtif)
                {
                    testPath = string.Format("{0}\\test_Png_{1}", outPutFile.DirectoryName, inPutFile.Name.Replace(".tif", ".png"));
                }
                else if (isExtiff)
                {
                    testPath = string.Format("{0}\\test_Png_{1}", outPutFile.DirectoryName, inPutFile.Name.Replace(".tiff", ".png"));
                }
                Dataset dstDs = srcDrv.CreateCopy(testPath, dswarp, 0, options, null, null);

                dstDs.FlushCache();
                #endregion

                #region Create PNG

                string file_name = Path.GetFileNameWithoutExtension(inPutFile.Name) + "_kml.png";
                string pngPath   = string.Format("{0}\\{1}", outPutFile.DirectoryName, file_name);

                Band band1 = dstDs.GetRasterBand(band); //특정 벤드 가져오기

                int startX = 0;
                int startY = 0;
                int width  = band1.XSize;
                int height = band1.YSize;

                double[] geot = new double[6];
                dstDs.GetGeoTransform(geot);

                double Xp = geot[0] + width * geot[1] + height * geot[2]; //우하단
                double Yp = geot[3] + width * geot[4] + height * geot[5]; //우하단

                north = geot[3];                                          //북
                west  = geot[0];                                          //서

                south = Yp;                                               //남
                east  = Xp;                                               //동

                int nBandSpace  = Gdal.GetDataTypeSize(DataType.GDT_Byte) / 8;
                int nPixelSpace = nBandSpace * dataset.RasterCount;
                int nLineSpace  = nPixelSpace * width;

                double[] buffer = new double[width * height];
                CPLErr   d      = band1.ReadRaster(startX, startY, width, height, buffer, width, height, 0, 0);

                double[] minmax = new double[2];
                band1.ComputeRasterMinMax(minmax, 0);

                Bitmap bitmap = new Bitmap(width, height);
                for (int x = 0; x < width; x++)
                {
                    for (int y = 0; y < height; y++)
                    {
                        double value = buffer[x + y * width];
                        if (!Double.IsNaN(value))
                        {
                            if (value >= minmax[0] && value <= minmax[1] && value != 0)
                            {
                                double colorValue = (value - minmax[0]) * 255 / (minmax[1] - minmax[0]);
                                Color  newColor   = Color.FromArgb(Convert.ToInt32(colorValue), Convert.ToInt32(colorValue), Convert.ToInt32(colorValue));
                                bitmap.SetPixel(x, y, newColor);
                            }
                            else
                            {
                                Color newColor = Color.FromArgb(0, 0, 0, 0);
                                bitmap.SetPixel(x, y, newColor);
                            }
                        }
                    }
                }
                bitmap.Save(pngPath, System.Drawing.Imaging.ImageFormat.Png);
                #endregion

                #region Create KML
                StreamWriter sw = new StreamWriter(outPut);
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                sw.WriteLine("<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/kml/2.2 http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd http://www.google.com/kml/ext/2.2 http://code.google.com/apis/kml/schema/kml22gx.xsd\">");
                sw.WriteLine("<Document id=\"radar\">");
                sw.WriteLine("\t<name>" + inPutFile.Name + "</name>");
                sw.WriteLine("\t<Snippet></Snippet>");
                sw.WriteLine("\t<GroundOverlay id=\"0\">");
                sw.WriteLine("\t\t<Snippet></Snippet>");
                sw.WriteLine("\t\t<drawOrder>1000</drawOrder>");
                sw.WriteLine("\t\t<name>" + inPutFile.Name + "</name>");
                sw.WriteLine("\t\t<Icon>\r\t\t\t<href>" + file_name + "</href>\r\t\t\t<viewBoundScale>1.0</viewBoundScale>\r\t\t</Icon>");
                sw.WriteLine("\t\t<LatLonBox>");
                sw.WriteLine("\t\t\t<north>" + north.ToString() + "</north>"); //북
                sw.WriteLine("\t\t\t<south>" + south.ToString() + "</south>"); //남
                sw.WriteLine("\t\t\t<east>" + east.ToString() + "</east>");    //동
                sw.WriteLine("\t\t\t<west>" + west.ToString() + "</west>");    //서
                sw.WriteLine("\t\t\t<rotation>0</rotation>");                  //회전
                sw.WriteLine("\t\t</LatLonBox>");
                sw.WriteLine("\t</GroundOverlay>");
                sw.WriteLine("</Document>");
                sw.WriteLine("</kml>");
                sw.Flush();
                sw.Close();
                sw.Dispose();
                #endregion

                dataset.Dispose();
                bitmap.Dispose();
                dstDs.Dispose();
                srcDrv.Dispose();
                dswarp.Dispose();
                File.Delete(testPath);
            }
            catch (Exception e)
            {
                return(false);
            }
            return(true);
        }
        public bool ChangeProjectionByUTM(string inPut, string outPut, int band = 1)
        {
            FileInfo inPutFile = new FileInfo(inPut);
            bool     isExtif   = false;
            bool     isExtiff  = false;

            //입력 파일이 없다면 종료
            if (!inPutFile.Exists)
            {
                return(false);
            }
            else
            {
                //입력 파일이 tif / tiff 파일이 아니라면 종료
                if (inPutFile.Extension != ".tif" && inPutFile.Extension != ".tiff")
                {
                    return(false);
                }

                if (inPutFile.Extension == ".tif")
                {
                    isExtif = true;
                }

                if (inPutFile.Extension == ".tiff")
                {
                    isExtiff = true;
                }
            }

            Gdal.AllRegister();

            try
            {
                #region Change projection

                string strWorldSinusoidal = "PROJCS[\"World_Sinusoidal\",GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433],AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Sinusoidal\"],PARAMETER[\"longitude_of_center\",0],PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]]]";
                string t_srs_wkt          = "GEOGCS[\"WGS84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS84\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.01745329251994328]]";

                Dataset dataset = Gdal.Open(inPut, Access.GA_ReadOnly);
                dataset.SetProjection(strWorldSinusoidal);
                string s_srs_wkt = dataset.GetProjectionRef();

                Dataset dswarp = Gdal.AutoCreateWarpedVRT(dataset, s_srs_wkt, t_srs_wkt, ResampleAlg.GRA_NearestNeighbour, 0);

                string[]          options = null;
                OSGeo.GDAL.Driver srcDrv  = Gdal.GetDriverByName("GTiff");

                FileInfo outPutFile = new FileInfo(outPut);
                string   testPath   = string.Empty;

                if (isExtif)
                {
                    testPath = string.Format("{0}\\test_Png_{1}", outPutFile.DirectoryName, inPutFile.Name.Replace(".tif", ".png"));
                }
                else
                if (isExtiff)
                {
                    testPath = string.Format("{0}\\test_Png_{1}", outPutFile.DirectoryName, inPutFile.Name.Replace(".tiff", ".png"));
                }

                Dataset dstDs = srcDrv.CreateCopy(testPath, dswarp, 0, options, null, null);

                #endregion

                #region Create PNG

                string file_name = Path.GetFileNameWithoutExtension(inPutFile.Name) + ".png";
                //string pngPath = string.Format("{0}\\{1}", outPutFile.DirectoryName, file_name);
                _strPngFile = string.Format("{0}\\{1}", outPutFile.DirectoryName, file_name);

                Band band1 = dstDs.GetRasterBand(band); //특정 벤드 가져오기

                int startX = 0;
                int startY = 0;
                int width  = band1.XSize;
                int height = band1.YSize;

                int nBandSpace  = Gdal.GetDataTypeSize(DataType.GDT_Byte) / 8;
                int nPixelSpace = nBandSpace * dataset.RasterCount;
                int nLineSpace  = nPixelSpace * width;

                double[] buffer = new double[width * height];
                CPLErr   d      = band1.ReadRaster(startX, startY, width, height, buffer, width, height, 0, 0);

                double[] minmax = new double[2];
                band1.ComputeRasterMinMax(minmax, 0);

                Bitmap bitmap = new Bitmap(width, height);
                for (int x = 0; x < width; x++)
                {
                    for (int y = 0; y < height; y++)
                    {
                        double value = buffer[x + y * width];
                        if (!Double.IsNaN(value))
                        {
                            if (value >= minmax[0] && value <= minmax[1] && value != 0)
                            {
                                double colorValue = (value - minmax[0]) * 255 / (minmax[1] - minmax[0]);
                                Color  newColor   = Color.FromArgb(Convert.ToInt32(colorValue), Convert.ToInt32(colorValue), Convert.ToInt32(colorValue));
                                bitmap.SetPixel(x, y, newColor);
                            }
                            else
                            {
                                Color newColor = Color.FromArgb(0, 0, 0, 0);
                                bitmap.SetPixel(x, y, newColor);
                            }
                        }
                    }
                }
                bitmap.Save(_strPngFile, System.Drawing.Imaging.ImageFormat.Png);
                #endregion

                #region Create a GeoTiff
                double north = 36.16465526448886; //북
                double south = 35.97362616042732; //남
                double east  = 127.5672085281825; //동
                double west  = 127.3435070025512; //서

                CheckGeoTransform(ref north, ref south, ref east, ref west, inPutFile);
                double[] newGeot = CalcGeoTransform(dstDs, north, south, east, west);

                OSGeo.GDAL.Driver driver     = Gdal.GetDriverByName("GTiff");
                Dataset           oldDataSet = Gdal.Open(_strPngFile, Access.GA_ReadOnly);
                Dataset           newDataSet = srcDrv.CreateCopy(outPut, oldDataSet, 0, null, null, null);

                newDataSet.SetProjection(dswarp.GetProjectionRef());
                newDataSet.SetGeoTransform(newGeot);

                #endregion

                oldDataSet.Dispose();
                newDataSet.Dispose();
                driver.Dispose();
                dataset.Dispose();
                bitmap.Dispose();
                dstDs.Dispose();
                srcDrv.Dispose();
                dswarp.Dispose();
                File.Delete(testPath);
                //File.Delete(pngPath);
            }
            catch (Exception e)
            {
                return(false);
            }

            return(true);
        }