GDAL在Winform下使用

 

注册语句 OSGeo.GDAL.Gdal.AllRegister()前加上:

    public Form1()
    {
        InitializeComponent();
        SharpMap.GdalConfiguration.ConfigureGdal();
        SharpMap.GdalConfiguration.ConfigureOgr();


        OSGeo.GDAL.Gdal.AllRegister();

        OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
    }
View Code

 

GdalConfiguration.cs

/******************************************************************************
 *
 * Name:     GdalConfiguration.cs.pp
 * Project:  GDAL CSharp Interface
 * Purpose:  A static configuration utility class to enable GDAL/OGR.
 * Author:   Felix Obermaier
 *
 ******************************************************************************
 * Copyright (c) 2012, Felix Obermaier
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *****************************************************************************/

using System;
using System.IO;
using System.Reflection;
using Gdal = OSGeo.GDAL.Gdal;
using Ogr = OSGeo.OGR.Ogr;

namespace SharpMap
{
    public static partial class GdalConfiguration
    {
        private static bool _configuredOgr;
        private static bool _configuredGdal;

        /// <summary>
        /// Function to determine which platform we're on
        /// </summary>
        private static string GetPlatform()
        {
            return IntPtr.Size == 4 ? "x86" : "x64";
        }


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

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


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

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

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

            var driverPath = Path.Combine(nativePath, "plugins");
            Environment.SetEnvironmentVariable("GDAL_DRIVER_PATH", driverPath);
            Gdal.SetConfigOption("GDAL_DRIVER_PATH", driverPath);

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

            var projSharePath = Path.Combine(gdalPath, "share");
            Environment.SetEnvironmentVariable("PROJ_LIB", projSharePath);
            Gdal.SetConfigOption("PROJ_LIB", projSharePath);
        }

        /// <summary>
        /// Method to ensure the static constructor is being called.
        /// </summary>
        /// <remarks>Be sure to call this function before using Gdal/Ogr/Osr</remarks>
        public static void ConfigureOgr()
        {
            if (_configuredOgr) return;

            // Register drivers
            Ogr.RegisterAll();
            _configuredOgr = true;

            PrintDriversOgr();
        }

        /// <summary>
        /// Method to ensure the static constructor is being called.
        /// </summary>
        /// <remarks>Be sure to call this function before using Gdal/Ogr/Osr</remarks>
        public static void ConfigureGdal()
        {
            if (_configuredGdal) return;

            // Register drivers
            Gdal.AllRegister();
            _configuredGdal = true;

            PrintDriversGdal();
        }

        private static void PrintDriversOgr()
        {
#if DEBUG
            var num = Ogr.GetDriverCount();
            for (var i = 0; i < num; i++)
            {
                var driver = Ogr.GetDriver(i);
                Console.WriteLine(string.Format("OGR {0}: {1}", i, driver.name));
            }
#endif
        }

        private static void PrintDriversGdal()
        {
#if DEBUG
            var num = Gdal.GetDriverCount();
            for (var i = 0; i < num; i++)
            {
                var driver = Gdal.GetDriver(i);
                Console.WriteLine(string.Format("GDAL {0}: {1}-{2}", i, driver.ShortName, driver.LongName));
            }
#endif
        }
    }
}
View Code

  int[] disband = { 4, 5, 6 };//波段选择

    private void btn_view_Click(object sender, EventArgs e)
    {
        ImageShow();
    }


    /// <summary>  
    /// GDAL栅格转换为位图  
    /// </summary>  
    /// <param name="ds">GDAL Dataset</param>  
    /// <param name="showRect">显示区域</param>  
    /// <param name="bandlist">需要显示的波段列表</param>  
    /// <returns>返回Bitmap对象</returns>  
    public Bitmap GetImage(OSGeo.GDAL.Dataset ds, Rectangle showRect, int[] bandlist)
    {
        int imgWidth = ds.RasterXSize;   //影像宽  
        int imgHeight = ds.RasterYSize;  //影像高  

        float ImgRatio = imgWidth / (float)imgHeight;  //影像宽高比  

        //获取显示控件大小  
        int BoxWidth = showRect.Width;
        int BoxHeight = showRect.Height;

        float BoxRatio = imgWidth / (float)imgHeight;  //显示控件宽高比  

        //计算实际显示区域大小,防止影像畸变显示  
        int BufferWidth, BufferHeight;
        if (BoxRatio >= ImgRatio)
        {
            BufferHeight = BoxHeight;
            BufferWidth = (int)(BoxHeight * ImgRatio);
        }
        else
        {
            BufferWidth = BoxWidth;
            BufferHeight = (int)(BoxWidth / ImgRatio);
        }

        //构建位图  
        Bitmap bitmap = new Bitmap(BufferWidth, BufferHeight,
                                 System.Drawing.Imaging.PixelFormat.Format24bppRgb);

        if (bandlist.Length == 3)     //RGB显示  
        {
            int[] r = new int[BufferWidth * BufferHeight];
            Band band1 = ds.GetRasterBand(bandlist[0]);
            band1.ReadRaster(0, 0, imgWidth, imgHeight, r, BufferWidth, BufferHeight, 0, 0);  //读取图像到内存  

            //为了显示好看,进行最大最小值拉伸显示  
            double[] maxandmin1 = { 0, 0 };
            band1.ComputeRasterMinMax(maxandmin1, 0);

            int[] g = new int[BufferWidth * BufferHeight];
            Band band2 = ds.GetRasterBand(bandlist[1]);
            band2.ReadRaster(0, 0, imgWidth, imgHeight, g, BufferWidth, BufferHeight, 0, 0);

            double[] maxandmin2 = { 0, 0 };
            band2.ComputeRasterMinMax(maxandmin2, 0);

            int[] b = new int[BufferWidth * BufferHeight];
            Band band3 = ds.GetRasterBand(bandlist[2]);
            band3.ReadRaster(0, 0, imgWidth, imgHeight, b, BufferWidth, BufferHeight, 0, 0);

            double[] maxandmin3 = { 0, 0 };
            band3.ComputeRasterMinMax(maxandmin3, 0);

            int i, j;
            for (i = 0; i < BufferWidth; i++)
            {
                for (j = 0; j < BufferHeight; j++)
                {
                    int rVal = Convert.ToInt32(r[i + j * BufferWidth]);
                    rVal = (int)((rVal - maxandmin1[0]) / (maxandmin1[1] - maxandmin1[0]) * 255);

                    int gVal = Convert.ToInt32(g[i + j * BufferWidth]);
                    gVal = (int)((gVal - maxandmin2[0]) / (maxandmin2[1] - maxandmin2[0]) * 255);

                    int bVal = Convert.ToInt32(b[i + j * BufferWidth]);
                    bVal = (int)((bVal - maxandmin3[0]) / (maxandmin3[1] - maxandmin3[0]) * 255);

                    Color newColor = Color.FromArgb(rVal, gVal, bVal);
                    bitmap.SetPixel(i, j, newColor);
                }
            }
        }
        else               //灰度显示  
        {
            int[] r = new int[BufferWidth * BufferHeight];
            Band band1 = ds.GetRasterBand(bandlist[0]);
            band1.ReadRaster(0, 0, imgWidth, imgHeight, r, BufferWidth, BufferHeight, 0, 0);

            double[] maxandmin1 = { 0, 0 };
            band1.ComputeRasterMinMax(maxandmin1, 0);

            int i, j;
            for (i = 0; i < BufferWidth; i++)
            {
                for (j = 0; j < BufferHeight; j++)
                {
                    int rVal = Convert.ToInt32(r[i + j * BufferWidth]);
                    rVal = (int)((rVal - maxandmin1[0]) / (maxandmin1[1] - maxandmin1[0]) * 255);

                    Color newColor = Color.FromArgb(rVal, rVal, rVal);
                    bitmap.SetPixel(i, j, newColor);
                }
            }
        }

        return bitmap;
    }


    private void ImageShow()
    {
        string filename = "";
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Filter = "Tiff文件|*.tif|Erdas img文件|*.img|Bmp文件|*.bmp|jpeg文件|*.jpg|所有文件|*.*";
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            filename = dlg.FileName;
        }

        if (filename == "")
        {
            MessageBox.Show("影像路径不能为空");
            return;
        }
        OSGeo.GDAL.Dataset ds = Gdal.Open(filename, Access.GA_ReadOnly);
        if (ds == null)
        {
            MessageBox.Show("影像打开失败");
            return;
        }
        Rectangle pictureRect = new Rectangle();
        pictureRect.X = 0;
        pictureRect.Y = 0;
        pictureRect.Width = this.pictureBox1.Width;
        pictureRect.Height = this.pictureBox1.Height;

       // int[] disband = { 3, 2, 1 };
        int[] disband = { 4, 5, 6 };

        Bitmap bitmap = GetImage(ds, pictureRect, disband);   //遥感影像构建位图  
        pictureBox1.Image = bitmap;                   //将位图传递给PictureBox控件进行显示  

    }
View Code

 

posted @ 2024-02-23 11:57  有翅膀的大象  阅读(8)  评论(0编辑  收藏  举报