-
Notifications
You must be signed in to change notification settings - Fork 305
Expand file tree
/
Copy pathGdalRasterLayer.cs
More file actions
2350 lines (2002 loc) · 91.6 KB
/
GdalRasterLayer.cs
File metadata and controls
2350 lines (2002 loc) · 91.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2007: Christian Graefe
// Copyright 2008: Dan Brecht and Joel Wilson
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Common.Logging;
using GeoAPI;
using GeoAPI.Geometries;
using OSGeo.GDAL;
using GeoAPI.CoordinateSystems;
using GeoAPI.CoordinateSystems.Transformations;
using NetTopologySuite.Index.Strtree;
using SharpMap.Base;
using SharpMap.CoordinateSystems;
using SharpMap.Data;
using SharpMap.Extensions.Data;
using Geometry = GeoAPI.Geometries.IGeometry;
using SharpMap.Rendering.Thematics;
using Point = System.Drawing.Point;
using Polygon = GeoAPI.Geometries.IPolygon;
namespace SharpMap.Layers
{
/// <summary>
/// Gdal raster image layer
/// </summary>
/// <remarks>
/// <example>
/// <code lang="C#">
/// myMap = new SharpMap.Map(new System.Drawing.Size(500,250);<br/>
/// SharpMap.Layers.GdalRasterLayer layGdal = new SharpMap.Layers.GdalRasterLayer("Blue Marble", @"C:\data\bluemarble.ecw");<br/>
/// myMap.Layers.Add(layGdal);<br/>
/// myMap.ZoomToExtents();<br/>
/// </code>
/// </example>
/// </remarks>
[Serializable]
public class GdalRasterLayer : Layer, ICanQueryLayer
{
private static readonly ILog _logger = LogManager.GetLogger(typeof (GdalRasterLayer));
static GdalRasterLayer()
{
GdalConfiguration.ConfigureGdal();
}
/// <summary>
/// Static Rtree that contains the extent and connection strings for gdal raster layer sub data sets.
/// </summary>
private STRtree<string> _subDataSets;
private IGeometryFactory _factory;
/// <summary>
/// Gets or sets a value indicating the geometry factory to use when creating geometries.
/// </summary>
/// <returns>A geometry factory</returns>
protected IGeometryFactory Factory
{
get
{
return _factory ?? (_factory = GeometryServiceProvider.Instance.CreateGeometryFactory(SRID));
}
set { _factory = value; }
}
/// <summary>
/// The extent of the layer
/// </summary>
protected Envelope _envelope;
/// <summary>
/// The inner dataset object
/// </summary>
protected Dataset _gdalDataset;
/// <summary>
/// The size of the raster image
/// </summary>
protected Size _imageSize;
// outer radius is feather between inner radius and rest of image
// outer radius is feather between inner radius and rest of image
private Point _stretchPoint;
/// <summary>
/// Flag indicating of geographic rotation is to be used.
/// </summary>
protected bool _useRotation;
#region accessors
/// <summary>
/// Gets the version of fwTools that was used to compile and test this GdalRasterLayer
/// </summary>
[Obsolete("FWTools no longer used", true)]
public static string FWToolsVersion
{
#pragma warning disable 612,618
get { return FwToolsHelper.FwToolsVersion; }
#pragma warning restore 612,618
}
/// <summary>
/// Gets or sets the filename of the raster file
/// </summary>
public string Filename { get; protected internal set; }
/// <summary>
/// Gets or sets a rectangle that is used to tile the image when rendering
/// </summary>
public Size TilingSize { get; set; }
/// <summary>
/// Gets or sets the bit depth of the raster file
/// </summary>
public int BitDepth { get; set; }
/// <summary>
/// Gets or set the projection of the raster file
/// </summary>
public string Projection { get; set; }
/// <summary>
/// Gets or sets to display IR Band
/// </summary>
public bool DisplayIR { get; set; }
/// <summary>
/// Gets or sets to display color InfraRed
/// </summary>
public bool DisplayCIR { get; set; }
/// <summary>
/// Gets or sets to display clip
/// </summary>
public bool ShowClip { get; set; }
/// <summary>
/// Gets or sets to display gamma
/// </summary>
public double Gamma { get; set; }
/// <summary>
/// Gets or sets to display gamma for Spot spot
/// </summary>
public double SpotGamma { get; set; }
/// <summary>
/// Gets or sets to display gamma for NonSpot
/// </summary>
public double NonSpotGamma { get; set; }
/// <summary>
/// Gets or sets to display red Gain
/// </summary>
public double[] Gain { get; set; }
/// <summary>
/// Gets or sets to display red Gain for Spot spot
/// </summary>
public double[] SpotGain { get; set; }
/// <summary>
/// Gets or sets to display red Gain for Spot spot
/// </summary>
public double[] NonSpotGain { get; set; }
/// <summary>
/// Gets or sets to display curve lut
/// </summary>
public List<int[]> CurveLut { get; set; }
/// <summary>
/// Correct Spot spot
/// </summary>
public bool HaveSpot { get; set; }
/// <summary>
/// Gets or sets to display curve lut for Spot spot
/// </summary>
public List<int[]> SpotCurveLut { get; set; }
/// <summary>
/// Gets or sets to display curve lut for NonSpot
/// </summary>
public List<int[]> NonSpotCurveLut { get; set; }
/// <summary>
/// Gets or sets the center point of the Spot spot
/// </summary>
public PointF SpotPoint { get; set; }
/// <summary>
/// Gets or sets the inner radius for the spot
/// </summary>
public double InnerSpotRadius { get; set; }
/// <summary>
/// Gets or sets the outer radius for the spot (feather zone)
/// </summary>
public double OuterSpotRadius { get; set; }
/// <summary>
/// Gets the true histogram
/// </summary>
public List<int[]> Histogram { get; private set; }
/// <summary>
/// Gets the quick histogram mean
/// </summary>
public double[] HistoMean
{
get
{
return null;// _histoMean;
}
}
/// <summary>
/// Gets the quick histogram brightness
/// </summary>
public double HistoBrightness
{
get
{
return double.NaN;
//_histoBrightness;
}
}
/// <summary>
/// Gets the quick histogram contrast
/// </summary>
public double HistoContrast
{
get
{
return double.NaN;
//_histoContrast;
}
}
/// <summary>
/// Gets the number of bands
/// </summary>
public int Bands { get; internal set; }
/// <summary>
/// Gets the GSD (Horizontal)
/// </summary>
public double GSD
{
get { return new GeoTransform(_gdalDataset).HorizontalPixelResolution; }
}
/// <summary>
/// Gets a value indicating if rotation information is to be used
/// </summary>
/// <returns><c>true</c> if rotation information is to be used.</returns>
public bool UseRotation
{
get { return _useRotation; }
set
{
if (value == _useRotation)
return;
_useRotation = value;
_envelope = GetExtent();
}
}
/// <summary>
/// Gets a value indicating the size of the raster data set.
/// </summary>
/// <returns>The size of the raster data set.</returns>
public Size Size
{
get { return _imageSize; }
}
/// <summary>
/// Gets or sets a value indicating if color correction is to be applied.
/// </summary>
public bool ColorCorrect { get; set; }
/// <summary>
/// Gets or sets a value indicating the portion of the image for which the <see cref="Histogram"/> is evaluated
/// </summary>
/// <returns>The portion of the image for which the <see cref="Histogram"/> is evaluated</returns>
public Rectangle HistoBounds { get; set; }
#pragma warning disable 1591
[Obsolete("Use CoordinateTransformation instead")]
public ICoordinateTransformation Transform
{
get { return CoordinateTransformation; }
protected set
{
CoordinateTransformation = value;
}
}
#pragma warning restore 1591
/// <summary>
/// Gets or sets a value indicating a color that is used as transparent color.
/// </summary>
/// <returns>A color that is interpreted as transparent.</returns>
public Color TransparentColor { get; set; }
/// <summary>
/// Gets or sets the minimum- and maximum pixel byte values of all raster bands.
/// <para/>Knowing these, you can scale the color range
/// </summary>
public Point StretchPoint
{
get
{
if (_stretchPoint.IsEmpty)
{
ComputeStretch();
}
return _stretchPoint;
}
set
{
_stretchPoint = value;
}
}
#endregion
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="layerName">The name of the layer</param>
protected GdalRasterLayer(string layerName)
{
SpotPoint = new PointF(0, 0);
Projection = "";
BitDepth = 8;
NonSpotGain = new double[] { 1, 1, 1, 1 };
SpotGain = new double[] { 1, 1, 1, 1 };
Gain = new double[] { 1, 1, 1, 1 };
NonSpotGamma = 1;
SpotGamma = 1;
Gamma = 1;
TransparentColor = Color.Empty;
ColorCorrect = true;
LayerName = layerName;
Gdal.AllRegister();
}
/// <summary>
/// initialize a Gdal based raster layer - from file
/// </summary>
/// <param name="strLayerName">Name of layer</param>
/// <param name="imageFilename">location of image</param>
public GdalRasterLayer(string strLayerName, string imageFilename) : this(strLayerName)
{
Filename = imageFilename;
OpenDataset(imageFilename);
}
/// <summary>
/// initialize a Gdal based raster layer - from buffer
/// </summary>
/// <param name="strLayerName">Name of layer</param>
/// <param name="imageBuffer">image buffer</param>
///
public GdalRasterLayer(string strLayerName, byte[] imageBuffer) : this(strLayerName)
{
// a layer data name
string memoryFileName = $"/vsimem/{strLayerName}Data";
Filename = memoryFileName;
OpenDataset(imageBuffer, memoryFileName);
}
/// <summary>
/// OpenDataset for buffer
/// </summary>
/// <param name="imageBuffer">image buffer</param>
/// <param name="memoryFileName">File Name in Memory</param>
protected void OpenDataset(byte[] imageBuffer, string memoryFileName)
{
try
{
Gdal.FileFromMemBuffer(memoryFileName, imageBuffer);
if (_logger.IsDebugEnabled)
_logger.Debug("Opening dataset " + memoryFileName);
_gdalDataset = Gdal.Open(memoryFileName, Access.GA_ReadOnly);
if (_logger.IsDebugEnabled)
_logger.Debug("Reading projection for " + memoryFileName);
// have gdal read the projection
Projection = _gdalDataset.GetProjectionRef();
if (!string.IsNullOrEmpty(Projection))
{
using (var p = new OSGeo.OSR.SpatialReference(null))
{
string wkt = Projection;
int res = p.ImportFromWkt(ref wkt);
int srid = 0;
if (res == 0)
{
if (Projection.StartsWith("PROJCS"))
int.TryParse(p.GetAuthorityCode("PROJCS"), out srid);
else if (Projection.StartsWith("GEOGCS"))
int.TryParse(p.GetAuthorityCode("GEOGCS"), out srid);
else
srid = p.AutoIdentifyEPSG();
}
SRID = srid;
}
}
if (_logger.IsDebugEnabled)
_logger.Debug("Read sizes" + memoryFileName);
_imageSize = new Size(_gdalDataset.RasterXSize, _gdalDataset.RasterYSize);
_envelope = GetExtent();
HistoBounds = new Rectangle((int)_envelope.MinX, (int)_envelope.MinY, (int)_envelope.Width,
(int)_envelope.Height);
//Bands = _gdalDataset.RasterCount;
if (_logger.IsDebugEnabled)
_logger.Debug("Dataset open, " + memoryFileName);
}
catch (Exception ex)
{
_gdalDataset = null;
throw new Exception("Couldn't load " + memoryFileName + "\n\n" + ex.Message + ex.InnerException);
}
finally
{
Gdal.Unlink(memoryFileName);
}
}
/// <summary>
/// OpenDataset for imageFile
/// </summary>
/// <param name="imageFilename">location of image</param>
protected void OpenDataset(string imageFilename)
{
try
{
if (_logger.IsDebugEnabled)
_logger.Debug("Opening dataset " + imageFilename);
_gdalDataset = Gdal.OpenShared(imageFilename, Access.GA_ReadOnly);
if (_logger.IsDebugEnabled)
_logger.Debug("Reading projection for " + imageFilename);
// have gdal read the projection
Projection = _gdalDataset.GetProjectionRef();
// no projection info found in the image...check for a prj
if (Projection == "" &&
File.Exists(imageFilename.Substring(0, imageFilename.LastIndexOf(".", StringComparison.CurrentCultureIgnoreCase)) + ".prj"))
{
Projection =
File.ReadAllText(imageFilename.Substring(0, imageFilename.LastIndexOf(".", StringComparison.CurrentCultureIgnoreCase)) + ".prj");
}
if (!String.IsNullOrEmpty(Projection))
{
using (var p = new OSGeo.OSR.SpatialReference(null))
{
var wkt = Projection;
var res = p.ImportFromWkt(ref wkt);
var srid = 0;
if (res == 0)
{
if (Projection.StartsWith("PROJCS"))
int.TryParse(p.GetAuthorityCode("PROJCS"), out srid);
else if (Projection.StartsWith("GEOGCS"))
int.TryParse(p.GetAuthorityCode("GEOGCS"), out srid);
else
srid = p.AutoIdentifyEPSG();
}
SRID = srid;
}
}
if (_logger.IsDebugEnabled)
_logger.Debug("Read sizes" + imageFilename);
_imageSize = new Size(_gdalDataset.RasterXSize, _gdalDataset.RasterYSize);
_envelope = GetExtent();
HistoBounds = new Rectangle((int) _envelope.MinX, (int) _envelope.MinY, (int) _envelope.Width,
(int) _envelope.Height);
//Bands = _gdalDataset.RasterCount;
if (_logger.IsDebugEnabled)
_logger.Debug("Dataset open, " + imageFilename);
}
catch (Exception ex)
{
_gdalDataset = null;
throw new Exception("Couldn't load " + imageFilename + "\n\n" + ex.Message + ex.InnerException);
}
}
/// <inheritdoc cref="DisposableObject.ReleaseManagedResources"/>
protected override void ReleaseManagedResources()
{
_factory = null;
if (_gdalDataset != null)
{
_gdalDataset.Dispose();
_gdalDataset = null;
}
base.ReleaseManagedResources();
}
/// <summary>
/// Returns the extent of the layer
/// </summary>
/// <returns>Bounding box corresponding to the extent of the features in the layer</returns>
public override Envelope Envelope
{
get { return _envelope.Copy(); }
}
/// <summary>
/// Renders the layer
/// </summary>
/// <param name="g">Graphics object reference</param>
/// <param name="map">Map which is rendered</param>
public override void Render(Graphics g, MapViewport map)
{
CheckDisposed();
ClearHistogram();
if (TilingSize.IsEmpty || (TilingSize.Width > map.Size.Width && TilingSize.Height > map.Size.Height))
{
if (_subDataSets != null)
{
foreach (string subDataSet in _subDataSets.Query(ToSource(map.Envelope)))
{
using (var ds = Gdal.Open(subDataSet, Access.GA_ReadOnly))
{
System.Diagnostics.Debug.WriteLine(ds.GetDescription());
GetPreview(ds, map.Size, g, map.Envelope, null, map);
}
}
}
else
GetPreview(_gdalDataset, map.Size, g, map.Envelope, null, map);
}
else
{
foreach (var tileEnvelope in Tile(map))
{
if (_subDataSets != null)
{
foreach (string subDataSet in _subDataSets.Query(ToSource(tileEnvelope)))
{
using (var ds = Gdal.Open(subDataSet, Access.GA_ReadOnly))
GetPreview(ds, map.Size, g, tileEnvelope, null, map);
}
}
else
GetPreview(_gdalDataset, map.Size, g, tileEnvelope, null, map);
}
}
//base.Render(g, map);
}
private void ClearHistogram()
{
var histogram = Histogram;
if (histogram == null)
{
histogram = new List<int[]>(Bands + 1);
for (int i = 0; i < Bands + 1; i++)
histogram.Add(new int[256]);
Histogram = histogram;
}
else
{
for (int i = 0; i < Bands + 1; i++)
Array.Clear(histogram[i], 0, 256);
}
}
private IEnumerable<Envelope> Tile(MapViewport map)
{
var lt = Point.Truncate(map.WorldToImage(map.Envelope.TopLeft()));
var rb = Point.Ceiling(map.WorldToImage(map.Envelope.BottomRight()));
var size = new Size(rb.X - lt.X, rb.Y - lt.Y);
var fullRect = new Rectangle(lt, size);
var overlapSize = new Size(2, 2);
for (int top = lt.Y; top < fullRect.Bottom; top+= TilingSize.Height )
{
for (int left = lt.X; left < fullRect.Right; left += TilingSize.Width)
{
var partialRect = new Rectangle(new Point(left - overlapSize.Width, top - overlapSize.Height),
Size.Add(TilingSize, overlapSize));
var res = new Envelope(map.ImageToWorld(partialRect.Location));
res.ExpandToInclude(map.ImageToWorld(new PointF(partialRect.Right, partialRect.Bottom)));
yield return res;
}
}
}
/// <summary>
/// Gets the spatial reference system of this layer
/// </summary>
/// <returns>A spatial reference system.</returns>
public ICoordinateSystem GetProjection()
{
try
{
return Session.Instance.CoordinateSystemServices.GetCoordinateSystem(SRID);
}
catch (Exception ee)
{
if (_logger.IsErrorEnabled)
_logger.Error("Error parsing projection", ee);
}
return null;
}
/// <summary>
/// Zoom to the native resolution
/// </summary>
/// <param name="map">The map object</param>
/// <returns>The zoom factor for a 1:1 Scale</returns>
public double GetOneToOne(Map map)
{
double dsWidth = _imageSize.Width;
double dsHeight = _imageSize.Height;
//double left, top, right, bottom;
double dblImgEnvW, dblImgEnvH, dblWindowGndW, dblWindowGndH, dblImginMapW, dblImginMapH;
var bbox = map.Envelope;
Size size = map.Size;
//// bounds of section of image to be displayed
//left = Math.Max(bbox.MinX, _envelope.MinX);
//top = Math.Min(bbox.MaxY, _envelope.MaxY);
//right = Math.Min(bbox.MaxX, _envelope.MaxX);
//bottom = Math.Max(bbox.MinY, _envelope.MinY);
// height and width of envelope of transformed image in ground space
dblImgEnvW = _envelope.Width;
dblImgEnvH = _envelope.Height;
// height and width of display window in ground space
dblWindowGndW = bbox.Width;
dblWindowGndH = bbox.Height;
// height and width of transformed image in pixel space
dblImginMapW = size.Width * (dblImgEnvW / dblWindowGndW);
dblImginMapH = size.Height * (dblImgEnvH / dblWindowGndH);
// image was not turned on its side
if ((dblImginMapW > dblImginMapH && dsWidth > dsHeight) ||
(dblImginMapW < dblImginMapH && dsWidth < dsHeight))
return map.Zoom * (dblImginMapW / dsWidth);
// image was turned on its side
else
return map.Zoom * (dblImginMapH / dsWidth);
}
/// <summary>
/// Calculates the Zoom value to nearest tiff internal resolution set
/// </summary>
/// <param name="map">A map</param>
/// <param name="bZoomIn">A flag indicating if zooming direction is magnify</param>
/// <returns>A zoom value</returns>
public double GetZoomNearestRSet(Map map, bool bZoomIn)
{
double dsWidth = _imageSize.Width;
double dsHeight = _imageSize.Height;
//double left, top, right, bottom;
double dblImgEnvW, dblImgEnvH, dblWindowGndW, dblWindowGndH, dblImginMapW, dblImginMapH;
double dblTempWidth;
Envelope bbox = map.Envelope;
Size size = map.Size;
//// bounds of section of image to be displayed
//left = Math.Max(bbox.MinX, _envelope.MinX);
//top = Math.Min(bbox.MaxY, _envelope.MaxY);
//right = Math.Min(bbox.MaxX, _envelope.MaxX);
//bottom = Math.Max(bbox.MinY, _envelope.MinY);
// height and width of envelope of transformed image in ground space
dblImgEnvW = _envelope.Width;
dblImgEnvH = _envelope.Height;
// height and width of display window in ground space
dblWindowGndW = bbox.Width;
dblWindowGndH = bbox.Height;
// height and width of transformed image in pixel space
dblImginMapW = size.Width * (dblImgEnvW / dblWindowGndW);
dblImginMapH = size.Height * (dblImgEnvH / dblWindowGndH);
// image was not turned on its side
if ((dblImginMapW > dblImginMapH && dsWidth > dsHeight) ||
(dblImginMapW < dblImginMapH && dsWidth < dsHeight))
dblTempWidth = dblImginMapW;
else
dblTempWidth = dblImginMapH;
// zoom level is within the r sets
if (dsWidth > dblTempWidth && (dsWidth / Math.Pow(2, 8)) < dblTempWidth)
{
if (bZoomIn)
{
for (int i = 0; i <= 8; i++)
{
if (dsWidth / Math.Pow(2, i) > dblTempWidth)
{
if (dsWidth / Math.Pow(2, i + 1) < dblTempWidth)
return map.Zoom * (dblTempWidth / (dsWidth / Math.Pow(2, i)));
}
}
}
else
{
for (int i = 8; i >= 0; i--)
{
if (dsWidth / Math.Pow(2, i) < dblTempWidth)
{
if (dsWidth / Math.Pow(2, i - 1) > dblTempWidth)
return map.Zoom * (dblTempWidth / (dsWidth / Math.Pow(2, i)));
}
}
}
}
return map.Zoom;
}
/// <summary>
/// Resets the <see cref="Histogram"/> bounds.
/// </summary>
public void ResetHistoRectangle()
{
HistoBounds = new Rectangle((int)_envelope.MinX, (int)_envelope.MinY,
(int)_envelope.Width, (int)_envelope.Height);
}
/// <summary>
/// Gets transform between raster's native projection and the map projection and sets it to <see cref="Layer.CoordinateTransformation"/>
/// </summary>
/// <param name="mapProjection">A map projection</param>
private void GetTransform(ICoordinateSystem mapProjection)
{
if (mapProjection == null || Projection == "")
{
CoordinateTransformation = null;
return;
}
// get our two projections
var srcCoord = GetProjection();
var tgtCoord = mapProjection;
// raster and map are in same projection, no need to transform
if (srcCoord.WKT == tgtCoord.WKT)
{
CoordinateTransformation = null;
return;
}
// create transform
CoordinateTransformation = Session.Instance.CoordinateSystemServices.CreateTransformation(srcCoord, tgtCoord);
ReverseCoordinateTransformation = Session.Instance.CoordinateSystemServices.CreateTransformation(tgtCoord, srcCoord);
}
private Envelope GetExtent()
{
var metadataDomainList = new HashSet<string>(_gdalDataset.GetMetadataDomainList());
if (metadataDomainList.Contains("SUBDATASETS"))
{
// Hack to clear number of bands
Bands = 0;
var envelope = new Envelope();
string[] subDataSets = _gdalDataset.GetMetadata("SUBDATASETS");
_subDataSets = new STRtree<string>();
for (int i = 0; i < subDataSets.Length; i++)
{
int namePos = subDataSets[i].IndexOf("_NAME=", StringComparison.Ordinal);
if (namePos < 0) continue;
string subDataSet = subDataSets[i].Substring(namePos + 6);
using (var ds = Gdal.Open(subDataSet, Access.GA_ReadOnly))
{
var tmp = GetExtent(ds);
_subDataSets.Insert(tmp, ds.GetDescription());
envelope.ExpandToInclude(tmp);
}
}
return envelope;
}
return GetExtent(_gdalDataset);
}
private Envelope GetExtent(Dataset dataSet)
{
if (dataSet == null)
return null;
// no rotation...use default transform
var geoTransform = new GeoTransform(dataSet);
if (geoTransform.IsIdentity)
geoTransform = new GeoTransform(-0.5, dataSet.RasterYSize + 0.5);
// image pixels
double dblW = dataSet.RasterXSize;
double dblH = dataSet.RasterYSize;
double left = geoTransform.EnvelopeLeft(dblW, dblH);
double right = geoTransform.EnvelopeRight(dblW, dblH);
double top = geoTransform.EnvelopeTop(dblW, dblH);
double bottom = geoTransform.EnvelopeBottom(dblW, dblH);
// Hack to set number of bands
if (Bands == 0)
Bands = dataSet.RasterCount;
return new Envelope(left, right, bottom, top);
}
/// <summary>
/// Gets the four corner coordinates of the raster data set.
/// </summary>
/// <returns>An array four corner coordinates of the raster data set</returns>
public Coordinate[] GetFourCorners()
{
var points = new Coordinate[4];
if (_gdalDataset != null)
{
var geoTrans = new double[6];
_gdalDataset.GetGeoTransform(geoTrans);
// no rotation...use default transform
if (!_useRotation && !HaveSpot || (DoublesAreEqual(geoTrans[0],0) && DoublesAreEqual(geoTrans[3],0)))
geoTrans = new[] { 999.5, 1, 0, 1000.5, 0, -1 };
points[0] = new Coordinate(geoTrans[0], geoTrans[3]);
points[1] = new Coordinate(geoTrans[0] + (geoTrans[1] * _imageSize.Width),
geoTrans[3] + (geoTrans[4] * _imageSize.Width));
points[2] = new Coordinate(geoTrans[0] + (geoTrans[1] * _imageSize.Width) + (geoTrans[2] * _imageSize.Height),
geoTrans[3] + (geoTrans[4] * _imageSize.Width) + (geoTrans[5] * _imageSize.Height));
points[3] = new Coordinate(geoTrans[0] + (geoTrans[2] * _imageSize.Height),
geoTrans[3] + (geoTrans[5] * _imageSize.Height));
// transform to map's projection
if (CoordinateTransformation != null)
{
for (var i = 0; i < 4; i++)
{
double[] dblPoint = CoordinateTransformation.MathTransform.Transform(new[] { points[i].X, points[i].Y });
points[i] = new Coordinate(dblPoint[0], dblPoint[1]);
}
}
}
return points;
}
/// <summary>
/// Gets a polygon outline of the raster data set boundary
/// </summary>
/// <returns>A polygon outline of the raster data set boundary</returns>
public Polygon GetFootprint()
{
var myRing = Factory.CreateLinearRing(GetFourCorners());
return Factory.CreatePolygon(myRing, null);
}
// applies map projection transfrom to get reprojected envelope
private void ApplyTransformToEnvelope()
{
_envelope = ToTarget(GetExtent(_gdalDataset));
HistoBounds = new Rectangle(
(int) Math.Floor(_envelope.MinX), (int) Math.Floor(_envelope.MinY),
(int) Math.Ceiling(_envelope.Width), (int) Math.Ceiling(_envelope.Width));
}
/// <summary>
/// Reprojects current raster to the given spatial reference system.
/// </summary>
/// <param name="cs">A spatial reference system.</param>
public void ReprojectToCoordinateSystem(ICoordinateSystem cs)
{
GetTransform(cs);
ApplyTransformToEnvelope();
}
// public method to set envelope and transform to new projection
/// <summary>
/// Method to set <see cref="Envelope"/> and <see cref="Layer.CoordinateTransformation"/> to the projection of the map
/// </summary>
/// <param name="map">The map</param>
public void ReprojectToMap(Map map)
{
ICoordinateSystem cs = null;
if (map.SRID > 0)
{
using (var p = new OSGeo.OSR.SpatialReference(null))
{
string wkt;
p.ImportFromEPSG(map.SRID);
p.ExportToWkt(out wkt);
cs = map.GetCoordinateSystem();
}
}
ReprojectToCoordinateSystem(cs);
}
/// <summary>
/// Renders the preview of the raster
/// </summary>
/// <param name="dataset">The raster data set</param>
/// <param name="size">Teh size</param>
/// <param name="g">A graphics object</param>
/// <param name="displayBbox">The bounding box of the display</param>
/// <param name="mapProjection">The spatial reference system of the map</param>
/// <param name="map">The map viewport</param>
protected virtual void GetPreview(Dataset dataset, Size size, Graphics g,
Envelope displayBbox, ICoordinateSystem mapProjection, MapViewport map)
{
//check if image is in bounding box
var dataSetBbox = ToTarget(GetExtent(dataset));
if (!displayBbox.Intersects(dataSetBbox))
return;
// Get the bounding box of the required data
dataSetBbox = ToSource(dataSetBbox.Intersection(displayBbox));
if (!NeedRotation(dataset))
{
GetNonRotatedPreview(dataset, size, g, displayBbox, mapProjection);
return;
}
var drawStart = DateTime.Now;
double totalReadDataTime = 0;
double totalTimeSetPixel = 0;