基于GDAL的栅格图像读写与转换——C#语言版

转载自GDAL官方帮助文档的代码

准备文件
编译好的gdal核心库gdal180.dll以及C#封装库gdal_wrap.dll、gdal_csharp.dll

引用说明
1. 将gdal180.dll、gdal_wrap.dll、 gdal_csharp.dll拷贝到程序的生成目录,并在项目里添加对gdal_csharp.dll库的引用。

2. 在要使用gdal的文件头部加上如下命名空间的声明:using OSGeo.GDAL;

/******************************************************************************
 * $Id$
 *
 * Name:     GDALRead.cs
 * Project:  GDAL CSharp Interface
 * Purpose:  A sample app to read GDAL raster data.
 * Author:   Tamas Szekeres, szekerest@gmail.com
 *
 ******************************************************************************
 * Copyright (c) 2007, Tamas Szekeres
 *
 * 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.Drawing;
using System.Drawing.Imaging;

using OSGeo.GDAL;


/**

 * <p>Title: GDAL C# GDALRead example.</p>
 * <p>Description: A sample app to read GDAL raster data.</p>
 * @author Tamas Szekeres (szekerest@gmail.com)
 * @version 1.0
 */



/// <summary>
/// A C# based sample to read GDAL raster data.
/// </summary>

class GDALRead {
       
        public static void usage() 

        { 
                Console.WriteLine("usage: gdalread {GDAL dataset name} {output file name} {overview}");
                System.Environment.Exit(-1);
        }
 
    public static void Main(string[] args) 
    {
        int iOverview = -1;
        if (args.Length < 2) usage();
        if (args.Length == 3) iOverview = int.Parse(args[2]);

        // Using early initialization of System.Console
        Console.WriteLine("");

        try 
        {
            /* -------------------------------------------------------------------- */
            /*      Register driver(s).                                             */
            /* -------------------------------------------------------------------- */
            Gdal.AllRegister();

            /* -------------------------------------------------------------------- */
            /*      Open dataset.                                                   */
            /* -------------------------------------------------------------------- */
            Dataset ds = Gdal.Open( args[0], Access.GA_ReadOnly );
               
            if (ds == null) 
            {
                Console.WriteLine("Can't open " + args[0]);
                System.Environment.Exit(-1);
            }

            Console.WriteLine("Raster dataset parameters:");
            Console.WriteLine("  Projection: " + ds.GetProjectionRef());
            Console.WriteLine("  RasterCount: " + ds.RasterCount);
            Console.WriteLine("  RasterSize (" + ds.RasterXSize + "," + ds.RasterYSize + ")");
           
            /* -------------------------------------------------------------------- */
            /*      Get driver                                                      */
            /* -------------------------------------------------------------------- */ 
            Driver drv = ds.GetDriver();

            if (drv == null) 
            {
                Console.WriteLine("Can't get driver.");
                System.Environment.Exit(-1);
            }
           
            Console.WriteLine("Using driver " + drv.LongName);

            /* -------------------------------------------------------------------- */
            /*      Get raster band                                                 */
            /* -------------------------------------------------------------------- */
            for (int iBand = 1; iBand <= ds.RasterCount; iBand++) 
            {
                Band band = ds.GetRasterBand(iBand);
                Console.WriteLine("Band " + iBand + " :");
                Console.WriteLine("   DataType: " + band.DataType);
                Console.WriteLine("   Size (" + band.XSize + "," + band.YSize + ")");
                Console.WriteLine("   PaletteInterp: " + band.GetRasterColorInterpretation().ToString());

                for (int iOver = 0; iOver < band.GetOverviewCount(); iOver++)
                {
                    Band over = band.GetOverview(iOver);
                    Console.WriteLine("      OverView " + iOver + " :");
                    Console.WriteLine("         DataType: " + over.DataType);
                    Console.WriteLine("         Size (" + over.XSize + "," + over.YSize + ")");
                    Console.WriteLine("         PaletteInterp: " + over.GetRasterColorInterpretation().ToString());
                }
            }

            /* -------------------------------------------------------------------- */
            /*      Processing the raster                                           */
            /* -------------------------------------------------------------------- */
            SaveBitmapBuffered(ds, args[1], iOverview);
           
        }
        catch (Exception e) 
        {
            Console.WriteLine("Application error: " + e.Message);
        }
    }

    private static void SaveBitmapBuffered(Dataset ds, string filename, int iOverview) 
    {
        // Get the GDAL Band objects from the Dataset
        Band redBand = ds.GetRasterBand(1);
       
                if (redBand.GetRasterColorInterpretation() == ColorInterp.GCI_PaletteIndex)
                {
                        SaveBitmapPaletteBuffered(ds, filename, iOverview);
                        return;
                }

                if (redBand.GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex)
                {
                        SaveBitmapGrayBuffered(ds, filename, iOverview);
                        return;
                }

                if (redBand.GetRasterColorInterpretation() != ColorInterp.GCI_RedBand)
                {
            Console.WriteLine("Non RGB images are not supported by this sample! ColorInterp = " + 
                redBand.GetRasterColorInterpretation().ToString());
                        return;
                }

                if (ds.RasterCount < 3) 
                {
                        Console.WriteLine("The number of the raster bands is not enough to run this sample");
                        System.Environment.Exit(-1);
                }

        if (iOverview >= 0 && redBand.GetOverviewCount() > iOverview) 
            redBand = redBand.GetOverview(iOverview);

        Band greenBand = ds.GetRasterBand(2);
       
                if (greenBand.GetRasterColorInterpretation() != ColorInterp.GCI_GreenBand)
                {
            Console.WriteLine("Non RGB images are not supported by this sample! ColorInterp = " + 
                greenBand.GetRasterColorInterpretation().ToString());
                        return;
                }

        if (iOverview >= 0 && greenBand.GetOverviewCount() > iOverview) 
            greenBand = greenBand.GetOverview(iOverview);

        Band blueBand = ds.GetRasterBand(3);
       
                if (blueBand.GetRasterColorInterpretation() != ColorInterp.GCI_BlueBand)
                {
            Console.WriteLine("Non RGB images are not supported by this sample! ColorInterp = " + 
                blueBand.GetRasterColorInterpretation().ToString());
                        return;
                }

        if (iOverview >= 0 && blueBand.GetOverviewCount() > iOverview) 
            blueBand = blueBand.GetOverview(iOverview);

        // Get the width and height of the raster
        int width = redBand.XSize;
        int height = redBand.YSize;

        // Create a Bitmap to store the GDAL image in
        Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);

        DateTime start = DateTime.Now;
       
        byte[] r = new byte[width * height];
        byte[] g = new byte[width * height];
        byte[] b = new byte[width * height];

        redBand.ReadRaster(0, 0, width, height, r, width, height, 0, 0);
        greenBand.ReadRaster(0, 0, width, height, g, width, height, 0, 0);
        blueBand.ReadRaster(0, 0, width, height, b, width, height, 0, 0);
        TimeSpan renderTime = DateTime.Now - start;
        Console.WriteLine("SaveBitmapBuffered fetch time: " + renderTime.TotalMilliseconds + " ms");

        int i, j;
        for (i = 0; i< width; i++) 
        {
            for (j=0; j<height; j++)
            {
                Color newColor = Color.FromArgb(Convert.ToInt32(r[i+j*width]),Convert.ToInt32(g[i+j*width]), Convert.ToInt32(b[i+j*width]));
                bitmap.SetPixel(i, j, newColor);
            }
        }

        bitmap.Save(filename);
    }

        private static void SaveBitmapPaletteBuffered(Dataset ds, string filename, int iOverview) 
        {
                // Get the GDAL Band objects from the Dataset
                Band band = ds.GetRasterBand(1);
        if (iOverview >= 0 && band.GetOverviewCount() > iOverview) 
            band = band.GetOverview(iOverview);

                ColorTable ct = band.GetRasterColorTable();
                if (ct == null)
                {
                        Console.WriteLine("   Band has no color table!");
                        return;
                }

                if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
                {
                        Console.WriteLine("   Only RGB palette interp is supported by this sample!");
                        return;
                }

                // Get the width and height of the Dataset
        int width = band.XSize;
        int height = band.YSize;

                // Create a Bitmap to store the GDAL image in
                Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);

                DateTime start = DateTime.Now;
       
                byte[] r = new byte[width * height];
               
                band.ReadRaster(0, 0, width, height, r, width, height, 0, 0);
                TimeSpan renderTime = DateTime.Now - start;
                Console.WriteLine("SaveBitmapBuffered fetch time: " + renderTime.TotalMilliseconds + " ms");

                int i, j;
                for (i = 0; i< width; i++) 
                {
                        for (j=0; j<height; j++)
                        {
                                ColorEntry entry = ct.GetColorEntry(r[i+j*width]);
                                Color newColor = Color.FromArgb(Convert.ToInt32(entry.c1),Convert.ToInt32(entry.c2), Convert.ToInt32(entry.c3));
                                bitmap.SetPixel(i, j, newColor);
                        }
                }

                bitmap.Save(filename);
        }

        private static void SaveBitmapGrayBuffered(Dataset ds, string filename, int iOverview) 
        {
                // Get the GDAL Band objects from the Dataset
                Band band = ds.GetRasterBand(1);
        if (iOverview >= 0 && band.GetOverviewCount() > iOverview) 
            band = band.GetOverview(iOverview);

                // Get the width and height of the Dataset
                int width = band.XSize;
        int height = band.YSize;

                // Create a Bitmap to store the GDAL image in
                Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);

                DateTime start = DateTime.Now;
       
                byte[] r = new byte[width * height];
               
                band.ReadRaster(0, 0, width, height, r, width, height, 0, 0);
                TimeSpan renderTime = DateTime.Now - start;
                Console.WriteLine("SaveBitmapBuffered fetch time: " + renderTime.TotalMilliseconds + " ms");

                int i, j;
                for (i = 0; i< width; i++) 
                {
                        for (j=0; j<height; j++)
                        {
                                Color newColor = Color.FromArgb(Convert.ToInt32(r[i+j*width]),Convert.ToInt32(r[i+j*width]), Convert.ToInt32(r[i+j*width]));
                                bitmap.SetPixel(i, j, newColor);
                        }
                }

                bitmap.Save(filename);
        }
}

Line	 
1
/******************************************************************************
2
 * $Id$
3
 *
4
 * Name:     GDALWrite.cs
5
 * Project:  GDAL CSharp Interface
6
 * Purpose:   sample app to write a GDAL raster.
7
 * Author:   Tamas Szekeres, szekerest@gmail.com
8
 *
9
 ******************************************************************************
10
 * Copyright (c) 2007, Tamas Szekeres
11
 *
12
 * Permission is hereby granted, free of charge, to any person obtaining a
13
 * copy of this software and associated documentation files (the "Software"),
14
 * to deal in the Software without restriction, including without limitation
15
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
16
 * and/or sell copies of the Software, and to permit persons to whom the
17
 * Software is furnished to do so, subject to the following conditions:
18
 *
19
 * The above copyright notice and this permission notice shall be included
20
 * in all copies or substantial portions of the Software.
21
 *
22
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28
 * DEALINGS IN THE SOFTWARE.
29
 *****************************************************************************/
30

31
using System;
32

33
using OSGeo.GDAL;
34

35

36
/**
37
 * <p>Title: GDAL C# GDALWrite example.</p>
38
 * <p>Description: A sample app to write a GDAL raster.</p>
39
 * @author Tamas Szekeres (szekerest@gmail.com)
40
 * @version 1.0
41
 */
42

43

44

45
/// <summary>
46
/// A C# based sample to write a GDAL raster.
47
/// </summary>
48

49
class GDALWrite {
50
       
51
        public static void usage() 
52

53
        { 
54
                Console.WriteLine("usage: gdalwrite {dataset name} {width} {height}");
55
                System.Environment.Exit(-1);
56
        }
57
 
58
    public static void Main(string[] args) 
59
    {
60

61
        if (args.Length < 1) usage();
62

63
        // Using early initialization of System.Console
64
        Console.WriteLine("Writing sample: " + args[0]);
65

66
        int bXSize, bYSize;
67
        int w, h;
68

69
        w = 100;
70
        h = 100;
71

72
        if (args.Length > 1)
73
            w = int.Parse(args[1]);
74

75
        if (args.Length > 2)
76
            h = int.Parse(args[2]);
77

78
        bXSize = w;
79
        bYSize = 1;
80

81
        //try
82
        {
83
            /* -------------------------------------------------------------------- */
84
            /*      Register driver(s).                                             */
85
            /* -------------------------------------------------------------------- */
86
            Gdal.AllRegister();
87
           
88
            /* -------------------------------------------------------------------- */
89
            /*      Get driver                                                      */
90
            /* -------------------------------------------------------------------- */ 
91
            Driver drv = Gdal.GetDriverByName("GTiff");
92

93
            if (drv == null) 
94
            {
95
                Console.WriteLine("Can't get driver.");
96
                System.Environment.Exit(-1);
97
            }
98
           
99
            Console.WriteLine("Using driver " + drv.LongName);
100

101
            /* -------------------------------------------------------------------- */
102
            /*      Open dataset.                                                   */
103
            /* -------------------------------------------------------------------- */
104
            string[] options = new string [] {"BLOCKXSIZE=" + bXSize, "BLOCKYSIZE=" + bYSize};
105
            Dataset ds = drv.Create(args[0], w, h, 1, DataType.GDT_Byte, options);
106
               
107
            if (ds == null) 
108
            {
109
                Console.WriteLine("Can't open " + args[0]);
110
                System.Environment.Exit(-1);
111
            }
112

113
            /* -------------------------------------------------------------------- */
114
            /*      Setting corner GCPs.                                            */
115
            /* -------------------------------------------------------------------- */
116
            GCP[] GCPs = new GCP[] { 
117
                new GCP(44.5, 27.5, 0, 0, 0, "info0", "id0"),
118
                new GCP(45.5, 27.5, 0, 100, 0, "info1", "id1"),
119
                new GCP(44.5, 26.5, 0, 0, 100, "info2", "id2"),
120
                new GCP(45.5, 26.5, 0, 100, 100, "info3", "id3")
121
            };
122
            ds.SetGCPs(GCPs, "");
123

124
            Band ba = ds.GetRasterBand(1);
125

126
            byte [] buffer = new byte [w * h];
127

128
            for (int i = 0; i < w; i++)
129
            {
130
                for (int j = 0; j < h; j++)
131
                {
132
                    buffer[i * w + j] = (byte)(i * 256 / w);
133
                }
134
            }
135

136
            ba.WriteRaster(0, 0, w, h, buffer, w, h, 0, 0);
137

138
            ba.FlushCache();
139
            ds.FlushCache();
140

141
        }
142
        /*catch (Exception e)
143
        {
144
            Console.WriteLine("Application error: " + e.Message);
145
        }*/
146
    }
147
}

Line	 
1
/******************************************************************************
2
 * $Id$
3
 *
4
 * Name:     GDALReadDirect.cs
5
 * Project:  GDAL CSharp Interface
6
 * Purpose:  A sample app to read GDAL raster data directly to a C# bitmap.
7
 * Author:   Tamas Szekeres, szekerest@gmail.com
8
 *
9
 ******************************************************************************
10
 * Copyright (c) 2007, Tamas Szekeres
11
 *
12
 * Permission is hereby granted, free of charge, to any person obtaining a
13
 * copy of this software and associated documentation files (the "Software"),
14
 * to deal in the Software without restriction, including without limitation
15
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
16
 * and/or sell copies of the Software, and to permit persons to whom the
17
 * Software is furnished to do so, subject to the following conditions:
18
 *
19
 * The above copyright notice and this permission notice shall be included
20
 * in all copies or substantial portions of the Software.
21
 *
22
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28
 * DEALINGS IN THE SOFTWARE.
29
 *****************************************************************************/
30

31
using System;
32
using System.Drawing;
33
using System.Drawing.Imaging;
34

35
using OSGeo.GDAL;
36

37

38
/**
39

40
 * <p>Title: GDAL C# GDALRead example.</p>
41
 * <p>Description: A sample app to read GDAL raster data directly to a C# bitmap.</p>
42
 * @author Tamas Szekeres (szekerest@gmail.com)
43
 * @version 1.0
44
 */
45

46

47

48
/// <summary>
49
/// A C# based sample to read GDAL raster data directly to a C# bitmap.
50
/// </summary>
51

52
class GDALReadDirect {
53
       
54
        public static void usage() 
55

56
        { 
57
                Console.WriteLine("usage: gdalread {GDAL dataset name} {output file name} {overview}");
58
                System.Environment.Exit(-1);
59
        }
60
 
61
    public static void Main(string[] args) 
62
    {
63

64
        int iOverview = -1;
65
        if (args.Length < 2) usage();
66
        if (args.Length == 3) iOverview = int.Parse(args[2]);
67

68
        // Using early initialization of System.Console
69
        Console.WriteLine("");
70

71
        try 
72
        {
73
            /* -------------------------------------------------------------------- */
74
            /*      Register driver(s).                                             */
75
            /* -------------------------------------------------------------------- */
76
            Gdal.AllRegister();
77

78
            /* -------------------------------------------------------------------- */
79
            /*      Open dataset.                                                   */
80
            /* -------------------------------------------------------------------- */
81
            Dataset ds = Gdal.Open( args[0], Access.GA_ReadOnly );
82
               
83
            if (ds == null) 
84
            {
85
                Console.WriteLine("Can't open " + args[0]);
86
                System.Environment.Exit(-1);
87
            }
88

89
            Console.WriteLine("Raster dataset parameters:");
90
            Console.WriteLine("  Projection: " + ds.GetProjectionRef());
91
            Console.WriteLine("  RasterCount: " + ds.RasterCount);
92
            Console.WriteLine("  RasterSize (" + ds.RasterXSize + "," + ds.RasterYSize + ")");
93
           
94
            /* -------------------------------------------------------------------- */
95
            /*      Get driver                                                      */
96
            /* -------------------------------------------------------------------- */ 
97
            Driver drv = ds.GetDriver();
98

99
            if (drv == null) 
100
            {
101
                Console.WriteLine("Can't get driver.");
102
                System.Environment.Exit(-1);
103
            }
104
           
105
            Console.WriteLine("Using driver " + drv.LongName);
106

107
            /* -------------------------------------------------------------------- */
108
            /*      Get raster band                                                 */
109
            /* -------------------------------------------------------------------- */
110
            for (int iBand = 1; iBand <= ds.RasterCount; iBand++) 
111
            {
112
                Band band = ds.GetRasterBand(iBand);
113
                Console.WriteLine("Band " + iBand + " :");
114
                Console.WriteLine("   DataType: " + band.DataType);
115
                Console.WriteLine("   Size (" + band.XSize + "," + band.YSize + ")");
116
                Console.WriteLine("   PaletteInterp: " + band.GetRasterColorInterpretation().ToString());
117

118
                for (int iOver = 0; iOver < band.GetOverviewCount(); iOver++)
119
                {
120
                    Band over = band.GetOverview(iOver);
121
                    Console.WriteLine("      OverView " + iOver + " :");
122
                    Console.WriteLine("         DataType: " + over.DataType);
123
                    Console.WriteLine("         Size (" + over.XSize + "," + over.YSize + ")");
124
                    Console.WriteLine("         PaletteInterp: " + over.GetRasterColorInterpretation().ToString());
125
                }
126
            }
127

128
            /* -------------------------------------------------------------------- */
129
            /*      Processing the raster                                           */
130
            /* -------------------------------------------------------------------- */
131
            SaveBitmapDirect(ds, args[1], iOverview);
132
           
133
        }
134
        catch (Exception e)
135
        {
136
            Console.WriteLine("Application error: " + e.Message);
137
        }
138
    }
139

140
    private static void SaveBitmapDirect(Dataset ds, string filename, int iOverview) 
141
    {
142
        // Get the GDAL Band objects from the Dataset
143
        Band redBand = ds.GetRasterBand(1);
144

145
        if (redBand.GetRasterColorInterpretation() == ColorInterp.GCI_PaletteIndex)
146
        {
147
            SaveBitmapPaletteDirect(ds, filename, iOverview);
148
            return;
149
        }
150

151
        if (redBand.GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex)
152
        {
153
            SaveBitmapGrayDirect(ds, filename, iOverview);
154
            return;
155
        }
156

157
        if (ds.RasterCount < 3) 
158
        {
159
            Console.WriteLine("The number of the raster bands is not enough to run this sample");
160
            System.Environment.Exit(-1);
161
        }
162

163
        if (iOverview >= 0 && redBand.GetOverviewCount() > iOverview) 
164
            redBand = redBand.GetOverview(iOverview);
165

166
        Band greenBand = ds.GetRasterBand(2);
167

168
        if (iOverview >= 0 && greenBand.GetOverviewCount() > iOverview) 
169
            greenBand = greenBand.GetOverview(iOverview);
170

171
        Band blueBand = ds.GetRasterBand(3);
172

173
        if (iOverview >= 0 && blueBand.GetOverviewCount() > iOverview) 
174
            blueBand = blueBand.GetOverview(iOverview);
175

176
        // Get the width and height of the Dataset
177
        int width = redBand.XSize;
178
        int height = redBand.YSize;
179

180
        // Create a Bitmap to store the GDAL image in
181
        Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
182

183
        DateTime start = DateTime.Now;
184
       
185
        // Use GDAL raster reading methods to read the image data directly into the Bitmap
186
        BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
187

188
        try 
189
        {
190
            int stride = bitmapData.Stride;
191
            IntPtr buf = bitmapData.Scan0;
192

193
            blueBand.ReadRaster(0, 0, width, height, buf, width, height, DataType.GDT_Byte, 4, stride);
194
            greenBand.ReadRaster(0, 0, width, height, new IntPtr(buf.ToInt32()+1), width, height, DataType.GDT_Byte, 4, stride);
195
            redBand.ReadRaster(0, 0, width, height, new IntPtr(buf.ToInt32()+2), width, height, DataType.GDT_Byte, 4, stride);
196
            TimeSpan renderTime = DateTime.Now - start;
197
            Console.WriteLine("SaveBitmapDirect fetch time: " + renderTime.TotalMilliseconds + " ms");
198
        }
199
        finally 
200
        {
201
            bitmap.UnlockBits(bitmapData);
202
        }
203

204
        bitmap.Save(filename);
205
    }
206

207
    private static void SaveBitmapPaletteDirect(Dataset ds, string filename, int iOverview) 
208
    {
209
        // Get the GDAL Band objects from the Dataset
210
        Band band = ds.GetRasterBand(1);
211
        if (iOverview >= 0 && band.GetOverviewCount() > iOverview) 
212
            band = band.GetOverview(iOverview);
213

214
        ColorTable ct = band.GetRasterColorTable();
215
        if (ct == null)
216
        {
217
            Console.WriteLine("   Band has no color table!");
218
            return;
219
        }
220

221
        if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
222
        {
223
            Console.WriteLine("   Only RGB palette interp is supported by this sample!");
224
            return;
225
        }
226

227
        // Get the width and height of the Dataset
228
        int width = band.XSize;
229
        int height = band.YSize;
230

231
        // Create a Bitmap to store the GDAL image in
232
        Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
233

234
        DateTime start = DateTime.Now;
235
       
236
        byte[] r = new byte[width * height];
237
               
238
        band.ReadRaster(0, 0, width, height, r, width, height, 0, 0);
239
        // Use GDAL raster reading methods to read the image data directly into the Bitmap
240
        BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
241

242
        try 
243
        {
244
            int iCol = ct.GetCount();
245
            ColorPalette pal = bitmap.Palette;
246
            for (int i = 0; i < iCol; i++)
247
            {
248
                ColorEntry ce = ct.GetColorEntry(i);
249
                pal.Entries[i] = Color.FromArgb(ce.c4, ce.c1, ce.c2, ce.c3);
250
            }
251
            bitmap.Palette = pal;
252
           
253
            int stride = bitmapData.Stride;
254
            IntPtr buf = bitmapData.Scan0;
255

256
            band.ReadRaster(0, 0, width, height, buf, width, height, DataType.GDT_Byte, 1, stride);
257
            TimeSpan renderTime = DateTime.Now - start;
258
            Console.WriteLine("SaveBitmapDirect fetch time: " + renderTime.TotalMilliseconds + " ms");
259
        }
260
        finally 
261
        {
262
            bitmap.UnlockBits(bitmapData);
263
        }
264

265
        bitmap.Save(filename);
266
    }
267

268
    private static void SaveBitmapGrayDirect(Dataset ds, string filename, int iOverview) 
269
    {
270
        // Get the GDAL Band objects from the Dataset
271
        Band band = ds.GetRasterBand(1);
272
        if (iOverview >= 0 && band.GetOverviewCount() > iOverview) 
273
            band = band.GetOverview(iOverview);
274

275
        // Get the width and height of the Dataset
276
        int width = band.XSize;
277
        int height = band.YSize;
278

279
        // Create a Bitmap to store the GDAL image in
280
        Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
281

282
        DateTime start = DateTime.Now;
283
       
284
        byte[] r = new byte[width * height];
285
               
286
        band.ReadRaster(0, 0, width, height, r, width, height, 0, 0);
287
        // Use GDAL raster reading methods to read the image data directly into the Bitmap
288
        BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
289

290
        try 
291
        {
292
            ColorPalette pal = bitmap.Palette; 
293
            for(int i = 0; i < 256; i++) 
294
                pal.Entries[i] = Color.FromArgb( 255, i, i, i ); 
295
            bitmap.Palette = pal;
296
           
297
            int stride = bitmapData.Stride;
298
            IntPtr buf = bitmapData.Scan0;
299

300
            band.ReadRaster(0, 0, width, height, buf, width, height, DataType.GDT_Byte, 1, stride);
301
            TimeSpan renderTime = DateTime.Now - start;
302
            Console.WriteLine("SaveBitmapDirect fetch time: " + renderTime.TotalMilliseconds + " ms");
303
        }
304
        finally 
305
        {
306
            bitmap.UnlockBits(bitmapData);
307
        }
308

309
        bitmap.Save(filename);
310
    }
311
}

Line	 
1
/******************************************************************************
2
 * $Id$
3
 *
4
 * Name:     createdata.cs
5
 * Project:  GDAL CSharp Interface
6
 * Purpose:  A sample app to create a spatial data source and a layer.
7
 * Author:   Tamas Szekeres, szekerest@gmail.com
8
 *
9
 ******************************************************************************
10
 * Copyright (c) 2007, Tamas Szekeres
11
 * Copyright (c) 2009-2010, Even Rouault <even dot rouault at mines-paris dot org>
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a
14
 * copy of this software and associated documentation files (the "Software"),
15
 * to deal in the Software without restriction, including without limitation
16
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
17
 * and/or sell copies of the Software, and to permit persons to whom the
18
 * Software is furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included
21
 * in all copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29
 * DEALINGS IN THE SOFTWARE.
30
 *****************************************************************************/
31

32

33
using System;
34

35
using OSGeo.OGR;
36
using OSGeo.OSR;
37

38

39
/**
40

41
 * <p>Title: GDAL C# createdata example.</p>
42
 * <p>Description: A sample app to create a spatial data source and a layer.</p>
43
 * @author Tamas Szekeres (szekerest@gmail.com)
44
 * @version 1.0
45
 */
46

47

48

49
/// <summary>
50
/// A C# based sample to create a layer.
51
/// </summary>
52

53
class CreateData {
54
       
55
        public static void usage() 
56

57
        { 
58
                Console.WriteLine("usage: createdata {data source name} {layername}");
59
                System.Environment.Exit(-1);
60
        }
61
 
62
        public static void Main(string[] args) {
63

64
                if (args.Length != 2) usage();
65

66
        // Using early initialization of System.Console
67
        Console.WriteLine("");
68

69
                /* -------------------------------------------------------------------- */
70
                /*      Register format(s).                                             */
71
                /* -------------------------------------------------------------------- */
72
        Ogr.RegisterAll();
73

74
                /* -------------------------------------------------------------------- */
75
                /*      Get driver                                                      */
76
                /* -------------------------------------------------------------------- */     
77
        Driver drv = Ogr.GetDriverByName("ESRI Shapefile");
78

79
                if (drv == null) 
80
                {
81
                        Console.WriteLine("Can't get driver.");
82
            System.Environment.Exit(-1);
83
                }
84

85
        // TODO: drv.name is still unsafe with lazy initialization (Bug 1339)
86
        //string DriverName = drv.name;
87
        //Console.WriteLine("Using driver " + DriverName);
88

89
                /* -------------------------------------------------------------------- */
90
                /*      Creating the datasource                                         */
91
                /* -------------------------------------------------------------------- */     
92

93
        DataSource ds = drv.CreateDataSource( args[0], new string[] {} );
94
        if (drv == null) 
95
        {
96
            Console.WriteLine("Can't create the datasource.");
97
            System.Environment.Exit(-1);
98
        }
99

100
        /* -------------------------------------------------------------------- */
101
        /*      Creating the layer                                              */
102
        /* -------------------------------------------------------------------- */
103

104
        Layer layer;
105
       
106
        int i;
107
        for(i=0;i<ds.GetLayerCount();i++)
108
        {
109
            layer = ds.GetLayerByIndex( i );
110
            if( layer != null && layer.GetLayerDefn().GetName() == args[1])
111
            {
112
                Console.WriteLine("Layer already existed. Recreating it.\n");
113
                ds.DeleteLayer(i);
114
                break;
115
            }
116
        }
117

118
        layer = ds.CreateLayer( args[1], null, wkbGeometryType.wkbPoint, new string[] {} );
119
        if( layer == null )
120
        {
121
            Console.WriteLine("Layer creation failed.");
122
            System.Environment.Exit(-1);
123
        }
124

125
        /* -------------------------------------------------------------------- */
126
        /*      Adding attribute fields                                         */
127
        /* -------------------------------------------------------------------- */
128

129
        FieldDefn fdefn = new FieldDefn( "Name", FieldType.OFTString );
130

131
        fdefn.SetWidth(32);
132

133
        if( layer.CreateField( fdefn, 1 ) != 0 )
134
        {
135
            Console.WriteLine("Creating Name field failed.");
136
            System.Environment.Exit(-1);
137
        }
138

139
                fdefn = new FieldDefn( "IntField", FieldType.OFTInteger );
140
                if( layer.CreateField( fdefn, 1 ) != 0 )
141
                {
142
                        Console.WriteLine("Creating IntField field failed.");
143
                        System.Environment.Exit(-1);
144
                }
145

146
                fdefn = new FieldDefn( "DbleField", FieldType.OFTReal );
147
                if( layer.CreateField( fdefn, 1 ) != 0 )
148
                {
149
                        Console.WriteLine("Creating DbleField field failed.");
150
                        System.Environment.Exit(-1);
151
                }
152

153
                fdefn = new FieldDefn( "DateField", FieldType.OFTDate );
154
                if( layer.CreateField( fdefn, 1 ) != 0 )
155
                {
156
                        Console.WriteLine("Creating DateField field failed.");
157
                        System.Environment.Exit(-1);
158
                }
159

160
        /* -------------------------------------------------------------------- */
161
        /*      Adding features                                                 */
162
        /* -------------------------------------------------------------------- */
163

164
        Feature feature = new Feature( layer.GetLayerDefn() );
165
        feature.SetField( "Name", "value" );
166
                feature.SetField( "IntField", (int)123 );
167
                feature.SetField( "DbleField", (double)12.345 );
168
                feature.SetField( "DateField", 2007, 3, 15, 18, 24, 30, 0 );
169

170
        Geometry geom = Geometry.CreateFromWkt("POINT(47.0 19.2)");
171
       
172
        if( feature.SetGeometry( geom ) != 0 )
173
        {
174
            Console.WriteLine( "Failed add geometry to the feature" );
175
            System.Environment.Exit(-1);
176
        }
177

178
        if( layer.CreateFeature( feature ) != 0 )
179
        {
180
            Console.WriteLine( "Failed to create feature in shapefile" );
181
            System.Environment.Exit(-1);
182
        }
183
       
184
                ReportLayer(layer);
185
        }
186

187
        public static void ReportLayer(Layer layer)
188
        {
189
                FeatureDefn def = layer.GetLayerDefn();
190
                Console.WriteLine( "Layer name: " + def.GetName() );
191
                Console.WriteLine( "Feature Count: " + layer.GetFeatureCount(1) );
192
                Envelope ext = new Envelope();
193
                layer.GetExtent(ext, 1);
194
                Console.WriteLine( "Extent: " + ext.MinX + "," + ext.MaxX + "," +
195
                        ext.MinY + "," + ext.MaxY);
196
               
197
                /* -------------------------------------------------------------------- */
198
                /*      Reading the spatial reference                                   */
199
                /* -------------------------------------------------------------------- */
200
        OSGeo.OSR.SpatialReference sr = layer.GetSpatialRef();
201
                string srs_wkt;
202
                if ( sr != null ) 
203
                {
204
                        sr.ExportToPrettyWkt( out srs_wkt, 1 );
205
                }
206
                else
207
                        srs_wkt = "(unknown)";
208

209

210
        Console.WriteLine( "Layer SRS WKT: " + srs_wkt );
211

212
                /* -------------------------------------------------------------------- */
213
                /*      Reading the fields                                              */
214
                /* -------------------------------------------------------------------- */
215
                Console.WriteLine("Field definition:");
216
                for( int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++ )
217
                {
218
                        FieldDefn fdef = def.GetFieldDefn( iAttr );
219
           
220
                        Console.WriteLine( fdef.GetNameRef() + ": " + 
221
                                fdef.GetFieldTypeName( fdef.GetFieldType() ) + " (" +
222
                                fdef.GetWidth() + "." +
223
                                fdef.GetPrecision() + ")");
224
                }
225

226
                /* -------------------------------------------------------------------- */
227
                /*      Reading the shapes                                              */
228
                /* -------------------------------------------------------------------- */
229
                Console.WriteLine( "" );
230
                Feature feat;
231
                while( (feat = layer.GetNextFeature()) != null )
232
                {
233
                        ReportFeature(feat, def);
234
                        feat.Dispose();
235
                }
236
        }
237

238
        public static void ReportFeature(Feature feat, FeatureDefn def)
239
        {
240
                Console.WriteLine( "Feature(" + def.GetName() + "): " + feat.GetFID() );
241
                for( int iField = 0; iField < feat.GetFieldCount(); iField++ )
242
                {
243
                        FieldDefn fdef = def.GetFieldDefn( iField );
244
           
245
                        Console.Write( fdef.GetNameRef() + " (" +
246
                                fdef.GetFieldTypeName(fdef.GetFieldType()) + ") = ");
247

248
                        if( feat.IsFieldSet( iField ) )
249
                                Console.WriteLine( feat.GetFieldAsString( iField ) );
250
                        else
251
                                Console.WriteLine( "(null)" );
252
           
253
                }
254

255
                if( feat.GetStyleString() != null )
256
                        Console.WriteLine( "  Style = " + feat.GetStyleString() );
257
   
258
                Geometry geom = feat.GetGeometryRef();
259
                if( geom != null )
260
                        Console.WriteLine( "  " + geom.GetGeometryName() + 
261
                                "(" + geom.GetGeometryType() + ")" );
262

263
                Envelope env = new Envelope();
264
                geom.GetEnvelope(env);
265
                Console.WriteLine( "   ENVELOPE: " + env.MinX + "," + env.MaxX + "," +
266
                        env.MinY + "," + env.MaxY);
267

268
                string geom_wkt;
269
                geom.ExportToWkt(out geom_wkt);
270
                Console.WriteLine( "  " + geom_wkt );
271

272
                Console.WriteLine( "" );
273
        }
274
}


转载自:https://blog.csdn.net/shumu_xzw/article/details/45767047

You may also like...

退出移动版