SvgImage.cs 13.1 KB
Newer Older
1
2
using System;
using System.Diagnostics;
Nir Noy's avatar
Nir Noy committed
3
using System.Drawing;
4
5
6
7
using System.Drawing.Drawing2D;
using System.IO;
using System.Net;
using Svg.Transforms;
Nir Noy's avatar
Nir Noy committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

namespace Svg
{
    /// <summary>
    /// Represents and SVG image
    /// </summary>
    [SvgElement("image")]
    public class SvgImage : SvgVisualElement
    {
        /// <summary>
		/// Initializes a new instance of the <see cref="SvgImage"/> class.
        /// </summary>
		public SvgImage()
        {
            Width = new SvgUnit(0.0f);
            Height = new SvgUnit(0.0f);
        }

26
27
        private GraphicsPath _path;

Nir Noy's avatar
Nir Noy committed
28
29
30
31
32
33
        /// <summary>
        /// Gets an <see cref="SvgPoint"/> representing the top left point of the rectangle.
        /// </summary>
        public SvgPoint Location
        {
            get { return new SvgPoint(X, Y); }
34
35
36
37
38
39
40
41
42
43
44
        }

        /// <summary>
        /// Gets or sets the aspect of the viewport.
        /// </summary>
        /// <value></value>
        [SvgAttribute("preserveAspectRatio")]
        public SvgAspectRatio AspectRatio
        {
            get { return this.Attributes.GetAttribute<SvgAspectRatio>("preserveAspectRatio"); }
            set { this.Attributes["preserveAspectRatio"] = value; }
Nir Noy's avatar
Nir Noy committed
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
        }

		[SvgAttribute("x")]
		public virtual SvgUnit X
		{
			get { return this.Attributes.GetAttribute<SvgUnit>("x"); }
			set { this.Attributes["x"] = value; }
		}

		[SvgAttribute("y")]
		public virtual SvgUnit Y
		{
			get { return this.Attributes.GetAttribute<SvgUnit>("y"); }
			set { this.Attributes["y"] = value; }
		}


		[SvgAttribute("width")]
		public virtual SvgUnit Width
		{
			get { return this.Attributes.GetAttribute<SvgUnit>("width"); }
			set { this.Attributes["width"] = value; }
		}

		[SvgAttribute("height")]
		public virtual SvgUnit Height
		{
			get { return this.Attributes.GetAttribute<SvgUnit>("height"); }
			set { this.Attributes["height"] = value; }
		}

		[SvgAttribute("href", SvgAttributeAttribute.XLinkNamespace)]
77
		public virtual string Href
Nir Noy's avatar
Nir Noy committed
78
		{
79
			get { return this.Attributes.GetAttribute<string>("href"); }
Nir Noy's avatar
Nir Noy committed
80
81
82
83
84
85
86
			set { this.Attributes["href"] = value; }
		}



        /// <summary>
        /// Gets the bounds of the element.
87
        /// </summary>
Nir Noy's avatar
Nir Noy committed
88
89
90
        /// <value>The bounds.</value>
        public override RectangleF Bounds
        {
91
92
93
94
95
96
            get
            {
                return TransformedBounds(new RectangleF(this.Location.ToDeviceValue(null, this),
                                      new SizeF(this.Width.ToDeviceValue(null, UnitRenderingType.Horizontal, this),
                                                this.Height.ToDeviceValue(null, UnitRenderingType.Vertical, this))));
            }
Nir Noy's avatar
Nir Noy committed
97
98
99
100
101
102
103
        }

        /// <summary>
        /// Gets the <see cref="GraphicsPath"/> for this element.
        /// </summary>
        public override GraphicsPath Path(ISvgRenderer renderer)
        {
104
105
106
107
108
109
110
111
112
113
114
115
116
          if (_path == null)
          {
            // Same size of rectangle can suffice to provide bounds of the image
            var rectangle = new RectangleF(Location.ToDeviceValue(renderer, this),
                SvgUnit.GetDeviceSize(Width, Height, renderer, this));

            _path = new GraphicsPath();
            _path.StartFigure();
            _path.AddRectangle(rectangle);
            _path.CloseFigure();
          }

          return _path;
Nir Noy's avatar
Nir Noy committed
117
118
119
120
        }

        /// <summary>
        /// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="Graphics"/> object.
121
        /// </summary>
Eric Domke's avatar
Eric Domke committed
122
        protected override void Render(ISvgRenderer renderer)
123
        {
C Moore's avatar
C Moore committed
124
125
126
            if (!Visible || !Displayable)
                return;

127
128
            if (Width.Value > 0.0f && Height.Value > 0.0f && this.Href != null)
            {
129
                var img = GetImage();
Eric Domke's avatar
Eric Domke committed
130
                if (img != null)
131
                {
Eric Domke's avatar
Eric Domke committed
132
133
134
135
                    RectangleF srcRect;
                    var bmp = img as Image;
                    var svg = img as SvgFragment;
                    if (bmp != null)
136
                    {
Eric Domke's avatar
Eric Domke committed
137
138
139
140
141
142
143
144
145
146
                        srcRect = new RectangleF(0, 0, bmp.Width, bmp.Height);
                    }
                    else if (svg != null)
                    {
                        srcRect = new RectangleF(new PointF(0, 0), svg.GetDimensions());
                    }
                    else
                    {
                        return;
                    }
147

Eric Domke's avatar
Eric Domke committed
148
                    var destClip = new RectangleF(this.Location.ToDeviceValue(renderer, this),
Andreas Niedermair's avatar
Andreas Niedermair committed
149
                                                  new SizeF(Width.ToDeviceValue(renderer, UnitRenderingType.Horizontal, this),
Eric Domke's avatar
Eric Domke committed
150
151
                                                            Height.ToDeviceValue(renderer, UnitRenderingType.Vertical, this)));
                    RectangleF destRect = destClip;
Andreas Niedermair's avatar
Andreas Niedermair committed
152

Eric Domke's avatar
Eric Domke committed
153
154
155
                    this.PushTransforms(renderer);
                    renderer.SetClip(new Region(destClip), CombineMode.Intersect);
                    this.SetClip(renderer);
156

157
158
                    SvgAspectRatio aspectRatio = AspectRatio ?? new SvgAspectRatio(SvgPreserveAspectRatio.xMidYMid);
                    if (aspectRatio.Align != SvgPreserveAspectRatio.none)
Eric Domke's avatar
Eric Domke committed
159
160
161
162
163
                    {
                        var fScaleX = destClip.Width / srcRect.Width;
                        var fScaleY = destClip.Height / srcRect.Height;
                        var xOffset = 0.0f;
                        var yOffset = 0.0f;
164

165
                        if (aspectRatio.Slice)
Eric Domke's avatar
Eric Domke committed
166
167
168
169
170
171
172
173
174
                        {
                            fScaleX = Math.Max(fScaleX, fScaleY);
                            fScaleY = Math.Max(fScaleX, fScaleY);
                        }
                        else
                        {
                            fScaleX = Math.Min(fScaleX, fScaleY);
                            fScaleY = Math.Min(fScaleX, fScaleY);
                        }
175

176
                        switch (aspectRatio.Align)
Eric Domke's avatar
Eric Domke committed
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
                        {
                            case SvgPreserveAspectRatio.xMinYMin:
                                break;
                            case SvgPreserveAspectRatio.xMidYMin:
                                xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2;
                                break;
                            case SvgPreserveAspectRatio.xMaxYMin:
                                xOffset = (destClip.Width - srcRect.Width * fScaleX);
                                break;
                            case SvgPreserveAspectRatio.xMinYMid:
                                yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2;
                                break;
                            case SvgPreserveAspectRatio.xMidYMid:
                                xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2;
                                yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2;
                                break;
                            case SvgPreserveAspectRatio.xMaxYMid:
                                xOffset = (destClip.Width - srcRect.Width * fScaleX);
                                yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2;
                                break;
                            case SvgPreserveAspectRatio.xMinYMax:
                                yOffset = (destClip.Height - srcRect.Height * fScaleY);
                                break;
                            case SvgPreserveAspectRatio.xMidYMax:
                                xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2;
                                yOffset = (destClip.Height - srcRect.Height * fScaleY);
                                break;
                            case SvgPreserveAspectRatio.xMaxYMax:
                                xOffset = (destClip.Width - srcRect.Width * fScaleX);
                                yOffset = (destClip.Height - srcRect.Height * fScaleY);
                                break;
208
                        }
209

Andreas Niedermair's avatar
Andreas Niedermair committed
210
                        destRect = new RectangleF(destClip.X + xOffset, destClip.Y + yOffset,
Eric Domke's avatar
Eric Domke committed
211
                                                    srcRect.Width * fScaleX, srcRect.Height * fScaleY);
212
                    }
Eric Domke's avatar
Eric Domke committed
213
214
215

                    if (bmp != null)
                    {
Vitaly Derbin's avatar
347    
Vitaly Derbin committed
216
217
218
219
                        if(Opacity==1F)
                            renderer.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel);
                        else
                            renderer.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel, Opacity);
Eric Domke's avatar
Eric Domke committed
220
221
222
223
224
225
226
227
228
229
230
231
232
                        bmp.Dispose();
                    }
                    else if (svg != null)
                    {
                        var currOffset = new PointF(renderer.Transform.OffsetX, renderer.Transform.OffsetY);
                        renderer.TranslateTransform(-currOffset.X, -currOffset.Y);
                        renderer.ScaleTransform(destRect.Width / srcRect.Width, destRect.Height / srcRect.Height);
                        renderer.TranslateTransform(currOffset.X + destRect.X, currOffset.Y + destRect.Y);
                        renderer.SetBoundable(new GenericBoundable(srcRect));
                        svg.RenderElement(renderer);
                        renderer.PopBoundable();
                    }

Andreas Niedermair's avatar
Andreas Niedermair committed
233

Eric Domke's avatar
Eric Domke committed
234
235
                    this.ResetClip(renderer);
                    this.PopTransforms(renderer);
236
237
238
239
240
241
                }
                // TODO: cache images... will need a shared context for this
                // TODO: support preserveAspectRatio, etc
            }
        }

242
243
244
245
246
        public object GetImage()
        {
            return this.GetImage(this.Href);
        }

247
        public object GetImage(string uriString)
248
        {
Andreas Niedermair's avatar
Andreas Niedermair committed
249
250
251
            string safeUriString;
            if (uriString.Length > 65519)
            {
252
253
                //Uri MaxLength is 65519 (https://msdn.microsoft.com/en-us/library/z6c2z492.aspx)
                safeUriString = uriString.Substring(0, 65519);
Andreas Niedermair's avatar
Andreas Niedermair committed
254
255
256
257
258
259
            }
            else
            {
                safeUriString = uriString;
            }

260
261
            try
            {
262
                var uri = new Uri(safeUriString, UriKind.RelativeOrAbsolute);
263

264
                // handle data/uri embedded images (http://en.wikipedia.org/wiki/Data_URI_scheme)
265
                if (uri.IsAbsoluteUri && uri.Scheme == "data")
266
267
268
269
270
271
272
273
                {
                    int dataIdx = uriString.IndexOf(",") + 1;
                    if (dataIdx <= 0 || dataIdx + 1 > uriString.Length)
                        throw new Exception("Invalid data URI");

                    // we're assuming base64, as ascii encoding would be *highly* unsusual for images
                    // also assuming it's png or jpeg mimetype
                    byte[] imageBytes = Convert.FromBase64String(uriString.Substring(dataIdx));
Eric Domke's avatar
Eric Domke committed
274
275
276
277
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        return Image.FromStream(stream);
                    }
278
279
                }

280
281
282
283
284
                if (!uri.IsAbsoluteUri)
                {
                    uri = new Uri(OwnerDocument.BaseUri, uri);
                }

285
286
287
288
289
                // should work with http: and file: protocol urls
                var httpRequest = WebRequest.Create(uri);

                using (WebResponse webResponse = httpRequest.GetResponse())
                {
Eric Domke's avatar
Eric Domke committed
290
                    using (var stream = webResponse.GetResponseStream())
291
                    {
Nir Noy's avatar
Nir Noy committed
292
293
                        if (stream.CanSeek)
                        {
Andreas Niedermair's avatar
Andreas Niedermair committed
294
                            stream.Position = 0;
Nir Noy's avatar
Nir Noy committed
295
                        }
Eric Domke's avatar
Eric Domke committed
296
297
298
299
                        if (uri.LocalPath.EndsWith(".svg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            var doc = SvgDocument.Open<SvgDocument>(stream);
                            doc.BaseUri = uri;
Eric Domke's avatar
Eric Domke committed
300
                            return doc;
Eric Domke's avatar
Eric Domke committed
301
302
303
304
305
                        }
                        else
                        {
                            return Bitmap.FromStream(stream);
                        }
306
                    }
307
308
309
310
                }
            }
            catch (Exception ex)
            {
311
                Trace.TraceError("Error loading image: '{0}', error: {1} ", uriString, ex.Message);
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
                return null;
            }
        }

        protected static MemoryStream BufferToMemoryStream(Stream input)
        {
            byte[] buffer = new byte[4 * 1024];
            int len;
            MemoryStream ms = new MemoryStream();
            while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, len);
            }
            ms.Seek(0, SeekOrigin.Begin);
            return ms;
Nir Noy's avatar
Nir Noy committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
        }


		public override SvgElement DeepCopy()
		{
			return DeepCopy<SvgImage>();
		}

		public override SvgElement DeepCopy<T>()
		{
 			var newObj = base.DeepCopy<T>() as SvgImage;
			newObj.Height = this.Height;
			newObj.Width = this.Width;
			newObj.X = this.X;
			newObj.Y = this.Y;
			newObj.Href = this.Href;
			return newObj;
		}
    }
346
}