Exemple #1
0
        private void _DatasetPng2File(Dataset ds, string sFileName)
        {
            OSGeo.GDAL.Driver drv       = Gdal.GetDriverByName("PNG");
            string[]          aryOption = { "" };

            Dataset dsOut = drv.CreateCopy(sFileName, ds, 0, aryOption, null, null);

            dsOut.FlushCache(); dsOut.Dispose();
        }
        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);
        }
Exemple #3
0
        private Dataset multi(Dataset oriDs, Dataset maskDs, string outPath)
        {
            int blockSize = 10240;
            int xSize     = oriDs.RasterXSize;
            int leftXSize = xSize;
            int xOffset   = 0;
            int ySize     = oriDs.RasterYSize;
            int leftYSize = ySize;
            int yOffset   = 0;

            progressInfo.SubTitle = "正在裁剪";
            while (leftYSize > 0)
            {
                int readYSize = (leftYSize > blockSize) ? blockSize : leftYSize;
                leftYSize = leftYSize - readYSize;

                xOffset   = 0;
                leftXSize = xSize;
                while (leftXSize > 0)
                {
                    int readXSize = (leftXSize > blockSize) ? blockSize : leftXSize;
                    leftXSize = leftXSize - readXSize;

                    int    totalSize = readXSize * readYSize;
                    byte[] oriData   = new byte[totalSize];
                    byte[] maskData  = new byte[totalSize];
                    oriDs.ReadRaster(xOffset, yOffset, readXSize, readYSize, oriData, readXSize, readYSize, 1, null, 0, 0, 0);
                    maskDs.ReadRaster(xOffset, yOffset, readXSize, readYSize, maskData, readXSize, readYSize, 1, null, 0, 0, 0);
                    for (int i = 0; i < totalSize; i++)
                    {
                        oriData[i] = (byte)(oriData[i] * maskData[i]);
                    }
                    oriDs.WriteRaster(xOffset, yOffset, readXSize, readYSize, oriData, readXSize, readYSize, 1, null, 0, 0, 0);

                    xOffset = xOffset + readXSize;
                }

                yOffset = yOffset + readYSize;
            }
            progressInfo.SubTitle = "写入影像";
            OSGeo.GDAL.Driver driver  = Gdal.GetDriverByName("GTiff");
            string[]          options = new string[]
            {
                "-co", "COMPRESS=LZW",
                "-co", "TILED=YES"
            };
            return(driver.CreateCopy(outPath, oriDs, 0, options, gdalProgressFunc, null));
        }
Exemple #4
0
        /// <summary>
        /// Brovey变换融合。融合前会将多光谱数据集的每一波段与全色数据集做直方图匹配。
        /// </summary>
        /// <param name="PanDS">全色数据集。</param>
        /// <param name="MSDS">多光谱数据集</param>
        /// <param name="PanCumu">全色数据集的累积概率表。</param>
        /// <param name="MSCumu">多光谱数据集的累积概率表。</param>
        /// <param name="MSBandList">多光谱数据集的波段组合。</param>
        /// <param name="OutDataType">输出数据类型。</param>
        /// <param name="OutPath">输出路径。</param>
        /// <returns>返回操作成功或失败。</returns>
        public static bool Brovey(OSGeo.GDAL.Dataset PanDS, OSGeo.GDAL.Dataset MSDS, double[][] PanCumu, double[][] MSCumu, int[] MSBandList, OSGeo.GDAL.DataType OutDataType, string OutPath)
        {
            try
            {
                if (PanDS == null)
                {
                    throw new ArgumentNullException("输入的全色数据集为空。");
                }
                if (PanDS.RasterCount > 1)
                {
                    throw new RankException("全色数据集波段大于1。");
                }
                if (MSDS == null)
                {
                    throw new ArgumentNullException("输入的多光谱数据集为空。");
                }
                if (String.IsNullOrWhiteSpace(OutPath.Trim()))
                {
                    throw new ArgumentNullException("输出路径为空或非法。");
                }
                OSGeo.GDAL.Driver Dri = OSGeo.GDAL.Gdal.GetDriverByName("Gtiff");
                if (Dri == null)
                {
                    throw new Exception("无法获取GDAL Driver。");
                }

                int panWidth  = PanDS.RasterXSize;
                int panHeight = PanDS.RasterYSize;
                int msWidth   = MSDS.RasterXSize;
                int msHeight  = MSDS.RasterYSize;
                //int rat = (int)Math.Ceiling((double)panHeight / msHeight);

                if (panWidth < msWidth)
                {
                    throw new RankException("全色数据集宽度小于多光谱数据集宽度。");
                }
                if (panHeight < msHeight)
                {
                    throw new RankException("全色数据集高度小于多光谱数据集高度。");
                }
                //if (rat <= 0)
                //    throw new ArgumentOutOfRangeException("全色高度:多光谱高度小于1。");

                FrmProgress FP = new FrmProgress()
                {
                    Text = "正在进行Brovey融合...",
                };

                Thread t = new Thread(() =>
                {
                    FP.ShowDialog();
                });
                t.SetApartmentState(ApartmentState.STA);
                t.Start();

                #region 预处理
                //创建临时文件,进行直方图匹配。
                string             HisMatFileName = Tools.Common.GetTempFileName();
                OSGeo.GDAL.Dataset MatchingDS     = Dri.CreateCopy(HisMatFileName, MSDS, 0, null, null, null);
                FP.Output("已创建直方图匹配临时文件\"" + HisMatFileName + "\"");
                for (int band = 1; band <= MSDS.RasterCount; band++)
                {
                    FP.Output("正在进行直方图匹配(" + band.ToString() + "/" + MSDS.RasterCount.ToString() + ")...");
                    Band b = Tools.BaseProcess.HistogramMatching(MSDS.GetRasterBand(band), PanDS.GetRasterBand(1), MSCumu[band - 1], PanCumu[0], OutDataType);
                    if (b == null)
                    {
                        throw new ArgumentNullException("直方图匹配返回波段为空。");
                    }
                    for (int row = 0; row < b.YSize; row++)
                    {
                        double[] tmp = new double[b.XSize];
                        b.ReadRaster(0, row, b.XSize, 1, tmp, b.XSize, 1, 0, 0);
                        MatchingDS.GetRasterBand(band).WriteRaster(0, row, MatchingDS.GetRasterBand(band).XSize, 1, tmp, MatchingDS.GetRasterBand(band).XSize, 1, 0, 0);
                        MatchingDS.FlushCache();
                        Thread.Sleep(1);
                    }
                }

                //创建临时文件,进行重采样。
                double[]           resamptmp;
                string             ResampFileName = Tools.Common.GetTempFileName();
                OSGeo.GDAL.Dataset ResampDS       = Dri.Create(ResampFileName, panWidth, panHeight, 3, MSDS.GetRasterBand(1).DataType, null);
                FP.Output("已创建重采样临时文件\"" + ResampFileName + "\"");
                //Tools.Common.CopyMetadata(PanDS, tmpDS);
                //Gdal.ReprojectImage(MSDS, tmpDS, null, null, 0, 0, 0, null, null);

                //将直方图匹配后的图像重采样。
                for (int i = 0; i < 3; i++)
                {
                    FP.Output("正在对直方图匹配后影像进行重采样(" + (i + 1).ToString() + "/" + "3)...");
                    resamptmp = new double[panWidth * panHeight];
                    MatchingDS.GetRasterBand(MSBandList[i]).ReadRaster(0, 0, msWidth, msHeight, resamptmp, panWidth, panHeight, 0, 0);
                    ResampDS.GetRasterBand(i + 1).WriteRaster(0, 0, panWidth, panHeight, resamptmp, panWidth, panHeight, 0, 0);
                    ResampDS.FlushCache();
                    Thread.Sleep(1);
                    if (FP.Canceled)
                    {
                        Thread.Sleep(500);

                        FP.Finish();
                        throw new OperationCanceledException("操作被用户取消。");
                    }
                }
                //释放直方图匹配图像资源。
                MatchingDS.Dispose();
                if (File.Exists(HisMatFileName))
                {
                    File.Delete(HisMatFileName);
                }
                FP.Output("已删除直方图匹配临时文件");
                #endregion

                //创建输出数据集。
                OSGeo.GDAL.Dataset DS = Dri.Create(OutPath, panWidth, panHeight, 3, OutDataType, null);
                FP.Output("已创建输出数据集\"" + OutPath + "\",数据类型为" + OutDataType.ToString() + "。");
                Tools.Common.CopyMetadata(PanDS, DS);

                double[]   p;
                double[][] ms;
                double[]   ds;

                for (int row = 0; row < panHeight; row++)
                {
                    FP.SetProgress2("正在处理", row + 1, panHeight, "行");
                    //将全色波段行读取进数组。
                    p = new double[panWidth];
                    PanDS.GetRasterBand(1).ReadRaster(0, row, panWidth, 1, p, panWidth, 1, 0, 0);

                    //将重采样后的多光谱行读取进数组。
                    ms    = new double[3][];
                    ms[0] = new double[panWidth];
                    ms[1] = new double[panWidth];
                    ms[2] = new double[panWidth];
                    ResampDS.GetRasterBand(1).ReadRaster(0, row, panWidth, 1, ms[0], panWidth, 1, 0, 0);
                    ResampDS.GetRasterBand(2).ReadRaster(0, row, panWidth, 1, ms[1], panWidth, 1, 0, 0);
                    ResampDS.GetRasterBand(3).ReadRaster(0, row, panWidth, 1, ms[2], panWidth, 1, 0, 0);

                    //遍历三波段
                    for (int bandcount = 0; bandcount < 3; bandcount++)
                    {
                        FP.SetProgress1("正在处理", bandcount + 1, 3, "波段");
                        ds = new double[panWidth];  //临时数组
                        for (long i = 0; i < panWidth; i++)
                        {
                            ds[i] = p[i] * ms[bandcount][i] / (ms[0][i] + ms[1][i] + ms[2][i]);                  //Brovey公式
                        }
                        DS.GetRasterBand(bandcount + 1).WriteRaster(0, row, panWidth, 1, ds, panWidth, 1, 0, 0); //计算完后的数据写入
                        DS.FlushCache();
                    }
                    Thread.Sleep(1);
                    if (FP.Canceled)
                    {
                        Thread.Sleep(500);

                        FP.Finish();
                        throw new OperationCanceledException("操作被用户取消。");
                    }
                }
                //释放重采样图像资源。
                ResampDS.Dispose();
                if (File.Exists(ResampFileName))
                {
                    File.Delete(ResampFileName);
                }
                FP.Output("已删除重采样临时文件");

                /*一次性读取一时爽,遇到大文件爆内存。
                *  一次性读取一时爽,遇到大文件爆内存。
                *  一次性读取一时爽,遇到大文件爆内存。*/
                //p = new double[panWidth * panHeight];
                //ms = new double[3][];
                //ms[0] = new double[panWidth * panHeight];
                //ms[1] = new double[panWidth * panHeight];
                //ms[2] = new double[panWidth * panHeight];

                //PanDS.GetRasterBand(1).ReadRaster(0, 0, panWidth, panHeight, p, panWidth, panHeight, 0, 0);
                //MSDS.GetRasterBand(MSBandList[0]).ReadRaster(0, 0, msWidth, msHeight, ms[0], panWidth, panHeight, 0, 0);
                //MSDS.GetRasterBand(MSBandList[1]).ReadRaster(0, 0, msWidth, msHeight, ms[1], panWidth, panHeight, 0, 0);
                //MSDS.GetRasterBand(MSBandList[2]).ReadRaster(0, 0, msWidth, msHeight, ms[2], panWidth, panHeight, 0, 0);

                //for (int bandcount = 0; bandcount < 3; bandcount++)
                //{
                //    ds = new double[panWidth * panHeight];
                //    for (int row = 0; row < panHeight; row++)
                //    {
                //        for (int col = 0; col < panWidth; col++)
                //        {
                //            ds[row * panWidth + col] = p[row * panWidth + col] * ms[bandcount][row * panWidth + col] / (ms[0][row * panWidth + col] + ms[1][row * panWidth + col] + ms[2][row * panWidth + col]);
                //        }
                //    }
                //    DS.GetRasterBand(bandcount + 1).WriteRaster(0, 0, panWidth, panHeight, ds, panWidth, panHeight, 0, 0);
                //    DS.FlushCache();
                //}

                FP.Finish();
                Dri.Dispose();
                DS.Dispose();
                return(true);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
                return(false);
            }
        }
        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);
        }
        public bool ImgToGeoTiff(string inPut, string outPut, int band = 1)
        {
            FileInfo inPutFile = new FileInfo(inPut);

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

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

                Band band1  = dataset.GetRasterBand(band); //특정 벤드 가져오기
                int  width  = band1.XSize;
                int  height = band1.YSize;

                int startX = 0;
                int startY = 0;

                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);

                #region 복사할 이미지 생성
                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);
                            }
                        }
                    }
                }
                FileInfo outPutFile = new FileInfo(outPut);
                string   pngPath    = string.Format("{0}\\{1}", outPutFile.DirectoryName, inPutFile.Name.Replace(".img", ".png"));
                bitmap.Save(pngPath, System.Drawing.Imaging.ImageFormat.Png);
                #endregion

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

                dstDs.SetProjection(dataset.GetProjection());

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

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

                File.Delete(pngPath);

                #endregion
            }
            catch (Exception e)
            {
                return(false);
            }

            return(true);
        }