1. 程式人生 > >基於GDAL的柵格影象讀寫與轉換——C#語言版

基於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, 
[email protected]
* ****************************************************************************** * 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 (
[email protected]
) * @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, [email protected]
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 ([email protected])
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, [email protected]
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 ([email protected])
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, [email protected]
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 ([email protected])
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
}


相關推薦

基於GDAL柵格影象轉換——C#語言

轉載自GDAL官方幫助文件的程式碼 準備檔案 編譯好的gdal核心庫gdal180.dll以及C#封裝庫gdal_wrap.dll、gdal_csharp.dll 引用說明 1. 將gdal180.dll、gdal_wrap.dll、 gdal_csharp.dll拷貝到

關於基於GDAL庫QT軟件平臺下C++語言開發使用說明

開發環境 用戶 寫入 imp 測試 windows系統 x64 href mage 背景前提   地理空間數據抽象庫(GDAL)是一個用於讀取和編寫柵格和矢量地理空間數據格式的計算機軟件庫,由開源地理空間基金會在許可的X / MIT風格免費軟件許可下發布。 作為一個庫,它為

資料結構演算法C語言分析概述

本節開始將帶領大家系統地學習資料結構,作為一門計算機專業大二學生的必修課程,該課程面對的目標人群為初步具備基本程式設計能力和程式設計思想的程式設計師(大一接觸了 C 語言或者 C++)。通過系統地學習資料結構,可以提高程式設計師分析問題和解決問題的能力。 首先,先來揭開資料結構的神祕面紗,看看什麼是資料結構

Python空間資料處理2: GDAL柵格影象格式轉換

在《GDAL讀寫遙感影象》中,有提到了GDAL支援多種資料格式,那麼,如何對這些格式進行相互轉換呢? 這其實非常簡單,僅在寫影象時稍加修改即可。例如,當我需要將某種柵格影象轉換為img格式時,只需將《GDAL讀寫遙感影象》中的程式碼進行以下修改: 第42行

實驗二 影象檔案的轉換(BMP轉YUV)

實驗二 影象檔案的讀寫和轉換(BMP轉YUV) 一、實驗基本原理 1.BMP點陣圖檔案格式 BMP(全稱Bitmap)是Windows作業系統中的標準影象檔案格式,可以分成兩類:裝置相關點陣圖(DDB)和裝置無關點陣圖(DIB),採用位對映儲存格式,除了影象深度可選(1

基於MGR+Atlas的分離嘗試,以及MGR+Keepalived+Atlas自動故障轉移+分離設想

字符 SQ keepalive 分享圖片 測試環境 物理 沒有 efi 列表 復制環境準備 讀寫分離理論上講,跟復制模式沒有關系,atlas負責的是重定向讀寫,至於復制模式自己選擇,這裏是測試環境,之前測試MGR的單機多實例,MGR單主模式的復制模式,就順便借助MG

C++從零開始區塊鏈:區塊鏈業務模組之基於boost的json

#include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> std::string BlockChain::GetJsonFromBlock(Bloc

NOIP複賽複習(三)檔案數論模板

檔案讀入讀出 假設題目名為“add”,那麼資料夾名為“add”,c++程式名為“add.cpp”,讀入檔名為“add.in”,輸出檔名為“add.out”。四個的拼寫均不可有誤,包括大小寫差異。千萬不要除錯後就忘記修改檔案讀入讀出了。  #include<cstdio&

隨機順序怎麼去理解

關於磁碟的讀寫效能曾經一直是我頭疼的地方,涉及研發或者測試時不清楚過程導致結果不盡人意。一起認識下關於磁碟的讀寫原理和順序讀寫,隨機讀寫。 首先磁碟是如何儲存資料的? 資訊儲存在硬盤裡,把它拆開也看不見裡面有任何東西,只有些碟片。假設,你用顯微鏡把碟片放大,會看見碟片表面凹凸不平,凸起的地方被磁化,凹的地

隨機順序怎麽去理解

reader 延遲 普通 格式化 () 數字 文件內容 刪除恢復 深度 關於磁盤的讀寫性能曾經一直是我頭疼的地方,涉及研發或者測試時不清楚過程導致結果不盡人意。一起認識下關於磁盤的讀寫原理和順序讀寫,隨機讀寫。 首先磁盤是如何存儲數據的? 信息存儲在硬盤裏,把它拆開也看不見

OpenCV例程之基本影象顯示

OpenCV是Intel®開源計算機視覺庫。它由一系列 C 函式和少量 C++ 類構成,實現了影象處理和計算機視覺方面的很多通用演算法。 1.  OpenCV與數字影象 在使用OpenCV做視覺或數字影象預處理時,需要讀入相機採集來的影象或視訊資訊。影象資料的獲取主要有以下

MySQL多資料來源 二(基於spring+aop實現分離)

一,為什麼要進行讀寫分離呢?   因為資料庫的“寫操作”操作是比較耗時的(寫上萬條條資料到Mysql的可能要1分鐘分鐘)。但是資料庫的“讀操作”卻比“寫操作”耗時要少的多(從Mysql的讀幾萬條資料條資料可能只要十秒鐘),而我們在開發過程中大多數也是查詢操作比較多。所以讀寫分離解決的是,資料庫的

Scala的檔案正則表示式

在本篇部落格中你將會學習並瞭解常用的檔案處理任務,例如讀取檔案的一行文字,本部落格的要點包含: 1. Source.fromFile(…).getLines.toArray 輸出檔案所有行 2. S

Java——IO流(三)字元流的拷貝、裝飾設計模式

1.字元流的學習(FileReader與FileWriter):字元流是可以直接讀寫字元的IO流(只讀或者只寫時使用字元流)          (1)字元流讀取字元就要先讀取到位元組資料,然後轉化為字元;如果要寫出字元,需要把字元轉化為位元組再寫出          (2)讀

實驗6  檔案多執行緒

1基礎知識 檔案與檔案路徑 檔案有兩個關鍵屬性:檔名和路徑。檔名中的最後一個句點之後的部分被稱為檔案的“副檔名”,它指明瞭檔案的型別。路徑指明瞭檔案在計算機上的位置。在Windows中,路徑書寫使用倒斜槓(\)作為資料夾之間的分隔符,而OS X和Linux中,則使用正

使用Spring基於應用層實現分離

背景 我們一般應用對資料庫而言都是“讀多寫少”,也就說對資料庫讀取資料的壓力比較大,有一個思路就是說採用資料庫叢集的方案, 其中一個是主庫,負責寫入資料,我們稱之為:寫庫; 其它都是從庫,負責讀取資料,我們稱之為:讀庫; 那麼,對我們的要求是: 1、

Unity下關於C#的檔案一(基於TXT的簡單)

Unity下關於C#的檔案讀寫(基於TXT和LitJson) NOTE (基本認識):其實.txt,.xml,.json這類檔案都屬於文字檔案,類似的還有.lrc歌詞檔案,.ini配置檔案,.reg登錄檔檔案等等,這類檔案所儲存的內容都是文字(即為字串),

磁碟系統基本概念以及磁碟的順序隨機

本文總結自 (1)《資料庫系統實現》 (2)知乎:https://www.zhihu.com/question/48254780 1.基本概念 2.細節 3.順序讀寫和隨機讀寫 1.基本概念 (1)磁碟組合 碟片=2盤面 主軸 磁軌 柱面 扇區 間隙 塊:對於理解資料庫

Python基礎知識之檔案修改

基本操作 f = open("file1", "r")  # 開啟檔案 first_line = f.readline() # 讀一行 data = f.read() # 讀取剩下所有內容,檔案大時候不要用 f.close()  #關閉檔案

無鎖程式設計:c++11基於atomic實現共享鎖(優先)

在多執行緒狀態下,對一個物件的讀寫需要加鎖,基於CAS指令的原子語句可以實現高效的執行緒間協調。關於CAS的概念參見下面的文章: 在c++11中CAS指令已經被封裝成了 非常方便使用的atomic模板類, 詳情參見: 以下程式碼利用atomic實現了