Exemple #1
0
        public override ImageSource Visit(SvgImageElement element, WpfDrawingContext context)
        {
            string sURI       = element.Href.AnimVal.Replace(" ", "");
            int    nColon     = sURI.IndexOf(":", StringComparison.OrdinalIgnoreCase);
            int    nSemiColon = sURI.IndexOf(";", StringComparison.OrdinalIgnoreCase);
            int    nComma     = sURI.IndexOf(",", StringComparison.OrdinalIgnoreCase);

            string sMimeType = sURI.Substring(nColon + 1, nSemiColon - nColon - 1);

            string sContent = SvgObject.RemoveWhitespace(sURI.Substring(nComma + 1));

            byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                            0, sContent.Length);

            switch (sMimeType.Trim())
            {
            case "image/svg+xml":
                using (var stream = new MemoryStream(imageBytes))
                    using (var reader = new FileSvgReader(context.Settings))
                        return(new DrawingImage(reader.Read(stream)));

            default:
                return(new EmbeddedBitmapSource(new MemoryStream(imageBytes)));
            }
        }
Exemple #2
0
        public override ImageSource Visit(SvgImageElement element, WpfDrawingContext context)
        {
            if (_imageCache == null)
            {
                _imageCache = new Dictionary <string, ImageSource>(StringComparer.Ordinal);
            }

            var imageId = element.Id;

            if (_imageCache.Count != 0)
            {
                if (!string.IsNullOrWhiteSpace(imageId) && _imageCache.ContainsKey(imageId))
                {
                    return(_imageCache[imageId]);
                }
            }

            var imageSource = this.GetImage(element, context);

            if (!string.IsNullOrWhiteSpace(imageId))
            {
                _imageCache[imageId] = imageSource;
            }

            return(imageSource);
        }
        public override void Render(ISvgRenderer renderer)
        {
            GraphicsWrapper graphics = ((GdiRenderer)renderer).GraphicsWrapper;
            SvgImageElement iElement = (SvgImageElement)element;
            //HttpResource resource = iElement.ReferencedResource;

            /*if (resource != null )
             * {*/
            ImageAttributes imageAttributes = new ImageAttributes();

            string sOpacity = iElement.GetPropertyValue("opacity");

            if (sOpacity.Length > 0)
            {
                double      opacity       = SvgNumber.ParseToFloat(sOpacity);
                ColorMatrix myColorMatrix = new ColorMatrix();
                myColorMatrix.Matrix00 = 1.00f;                         // Red
                myColorMatrix.Matrix11 = 1.00f;                         // Green
                myColorMatrix.Matrix22 = 1.00f;                         // Blue
                myColorMatrix.Matrix33 = (float)opacity;                // alpha
                myColorMatrix.Matrix44 = 1.00f;                         // w

                imageAttributes.SetColorMatrix(myColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            }

            float width  = (float)iElement.Width.AnimVal.Value;
            float height = (float)iElement.Height.AnimVal.Value;

            Rectangle destRect = new Rectangle();

            destRect.X      = Convert.ToInt32(iElement.X.AnimVal.Value);
            destRect.Y      = Convert.ToInt32(iElement.Y.AnimVal.Value);
            destRect.Width  = Convert.ToInt32(width);
            destRect.Height = Convert.ToInt32(height);

            Image image;

            if (iElement.IsSvgImage)
            {
                SvgWindow wnd = getSvgWindow();
                gdiRenderer.BackColor = Color.Empty;
                gdiRenderer.Render(wnd.Document as SvgDocument);

                //wnd.Render();
                image = gdiRenderer.RasterImage;
                image.Save(@"c:\inlinesvg.png", ImageFormat.Png);
            }
            else
            {
                image = iElement.Bitmap;
            }

            if (image != null)
            {
                graphics.DrawImage(this, image, destRect, 0f, 0f, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes);
            }
            //}
        }
        private SvgWindow getSvgWindow()
        {
            SvgImageElement iElm = Element as SvgImageElement;
            SvgWindow       wnd  = iElm.SvgWindow;

            wnd.Renderer       = gdiRenderer;
            gdiRenderer.Window = wnd;
            return(wnd);
        }
Exemple #5
0
        public override ImageSource Visit(SvgImageElement element, WpfDrawingContext context)
        {
            if (_imageCache == null)
            {
                _imageCache = new Dictionary <string, ImageSource>(StringComparer.Ordinal);
            }

            var imageId = element.Id;

            if (_imageCache.Count != 0)
            {
                if (!string.IsNullOrWhiteSpace(imageId) && _imageCache.ContainsKey(imageId))
                {
                    var cachedSource = _imageCache[imageId];
                    if (cachedSource != null)
                    {
                        var cachedImage = cachedSource as BitmapImage;
                        if (cachedImage != null)
                        {
                            var imageUri = cachedImage.UriSource;
                            if (imageUri != null)
                            {
                                if (imageUri.IsFile && File.Exists(imageUri.LocalPath))
                                {
                                    return(cachedImage);
                                }
                                _imageCache.Remove(imageId);
                            }
                            else if (cachedImage.StreamSource != null)
                            {
                                return(cachedImage);
                            }
                        }
                        else
                        {
                            return(cachedSource);
                        }
                    }
                    else
                    {
                        _imageCache.Remove(imageId);
                    }
                }
            }

            var imageSource = this.GetImage(element, context);

            if (!string.IsNullOrWhiteSpace(imageId))
            {
                _imageCache[imageId] = imageSource;
            }

            return(imageSource);
        }
        private ImageSource GetImage(SvgImageElement element, WpfDrawingContext context)
        {
            if (context != null && context.Settings.IncludeRuntime == false)
            {
                return(null);
            }

            var comparer = StringComparison.OrdinalIgnoreCase;

            string sURI       = element.Href.AnimVal.Replace(" ", string.Empty);
            int    nColon     = sURI.IndexOf(":", comparer);
            int    nSemiColon = sURI.IndexOf(";", comparer);
            int    nComma     = sURI.IndexOf(",", comparer);

            string sMimeType = sURI.Substring(nColon + 1, nSemiColon - nColon - 1);

            string sContent = SvgObject.RemoveWhitespace(sURI.Substring(nComma + 1));

            byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(), 0, sContent.Length);
            bool   isGZiped   = sContent.StartsWith(SvgConstants.GZipSignature, StringComparison.Ordinal);
            bool   isSvgOrXml = sContent.StartsWith(SvgConstants.SvgSignature, StringComparison.Ordinal) ||
                                sContent.StartsWith(SvgConstants.XmlSignature, StringComparison.Ordinal);

            if (string.Equals(sMimeType, "image/svg+xml", comparer) || isSvgOrXml)
            {
                if (isGZiped)
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
                        {
                            using (var reader = new FileSvgReader(context.Settings, true))
                            {
                                return(new DrawingImage(reader.Read(zipStream)));
                            }
                        }
                    }
                }
                else
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (var reader = new FileSvgReader(context.Settings, true))
                        {
                            return(new DrawingImage(reader.Read(stream)));
                        }
                    }
                }
            }

            return(new EmbeddedBitmapSource(new MemoryStream(imageBytes)));
        }
Exemple #7
0
        public void TestHttpPng()
        {
            string          url = "http://www.protocol7.com/images/logo.png";
            SvgImageElement elm = getElm(url);

            Assert.AreEqual(url, elm.Href.AnimVal);

            Assert.AreEqual(false, elm.IsSvgImage);
            Assert.IsNull(elm.SvgWindow);

            Assert.IsNotNull(elm.Bitmap);
            Assert.AreEqual(350, elm.Bitmap.Width);
            Assert.AreEqual(128, elm.Bitmap.Height);
        }
Exemple #8
0
        private Image GetBitmap(SvgImageElement element)
        {
            if (!element.IsSvgImage)
            {
                if (!element.Href.AnimVal.StartsWith("data:"))
                {
                    SvgUriReference svgUri   = element.UriReference;
                    Uri             imageUri = new Uri(svgUri.AbsoluteUri);
                    if (imageUri.IsFile && File.Exists(imageUri.LocalPath))
                    {
                        return(Bitmap.FromFile(imageUri.LocalPath));
                    }

                    WebResponse resource = svgUri.ReferencedResource;
                    if (resource == null)
                    {
                        return(null);
                    }

                    Stream stream = resource.GetResponseStream();
                    if (stream == null)
                    {
                        return(null);
                    }

                    return(Bitmap.FromStream(stream));
                }
                else
                {
                    string sURI       = element.Href.AnimVal;
                    int    nColon     = sURI.IndexOf(":");
                    int    nSemiColon = sURI.IndexOf(";");
                    int    nComma     = sURI.IndexOf(",");

                    string sMimeType = sURI.Substring(nColon + 1, nSemiColon - nColon - 1);

                    string sContent = sURI.Substring(nComma + 1);
                    byte[] bResult  = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                                  0, sContent.Length);

                    MemoryStream ms = new MemoryStream(bResult);

                    return(Bitmap.FromStream(ms));
                }
            }
            else
            {
                return(null);
            }
        }
Exemple #9
0
        private SvgWindow GetSvgWindow()
        {
            if (_embeddedRenderer == null)
            {
                _embeddedRenderer = new GdiGraphicsRenderer();
            }

            SvgImageElement iElm = this.Element as SvgImageElement;
            SvgWindow       wnd  = iElm.SvgWindow;

            wnd.Renderer = _embeddedRenderer;

            _embeddedRenderer.Window = wnd;

            return(wnd);
        }
Exemple #10
0
        private SvgWindow GetSvgWindow()
        {
            if (_embeddedRenderer == null)
            {
                _embeddedRenderer = new WpfDrawingRenderer();
            }

            SvgImageElement iElm = (SvgImageElement)this.Element;
            SvgWindow       wnd  = iElm.SvgWindow;

            wnd.Renderer = _embeddedRenderer;

            _embeddedRenderer.Window = wnd;

            return(wnd);
        }
        private SvgWindow GetSvgWindow(GdiGraphics graphics)
        {
            SvgImageElement iElm = this.Element as SvgImageElement;
            SvgWindow       wnd  = iElm.SvgWindow;

            if (_embeddedRenderer == null)
            {
                _embeddedRenderer = new GdiGraphicsRenderer(graphics, wnd);
            }
            else
            {
                wnd.Renderer             = _embeddedRenderer;
                _embeddedRenderer.Window = wnd;
            }

            return(wnd);
        }
        private ImageSource GetBitmapSource(SvgImageElement element, WpfDrawingContext context)
        {
            ImageSource imageSource = this.GetBitmap(element, context);

            if (imageSource == null)
            {
                return(imageSource);
            }

            SvgColorProfileElement colorProfile = (SvgColorProfileElement)element.ColorProfile;

            if (colorProfile == null || !(imageSource is BitmapSource))
            {
                return(imageSource);
            }
            BitmapSource bitmapSource = (BitmapSource)imageSource;
            BitmapFrame  inputFrame   = BitmapFrame.Create(bitmapSource);

            SvgUriReference svgUri     = colorProfile.UriReference;
            Uri             profileUri = new Uri(svgUri.AbsoluteUri);

            ColorContext colorContext = new ColorContext(new Uri(svgUri.AbsoluteUri));

            var colorContexts = new ReadOnlyCollection <ColorContext>(new ColorContext[] { colorContext });

            BitmapFrame outputFrame   = BitmapFrame.Create(inputFrame, null, null, colorContexts);
            var         bitmapImage   = new BitmapImage();
            var         bitmapEncoder = new PngBitmapEncoder();

            bitmapEncoder.Frames.Add(outputFrame);

            using (var stream = new MemoryStream())
            {
                bitmapEncoder.Save(stream);
                stream.Seek(0, SeekOrigin.Begin);

                bitmapImage.BeginInit();
                bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
            }

//            bitmapImage.Freeze();

            return(bitmapImage);
        }
Exemple #13
0
    public void TestDataImage()
    {
        string      testData = "<?xml version='1.0'?>\n<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><image id='theImage' width='50' height='50' xlink:href='data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAwAAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSpa/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uisF81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PHhhx4dbgYKAAA7'/></svg>";
        SvgWindow   wnd      = new SvgWindow(50, 50, null);
        SvgDocument doc      = new SvgDocument(wnd);

        doc.LoadXml(testData);

        SvgImageElement imgElm = doc.GetElementById("theImage") as SvgImageElement;

        Assert.IsNotNull(imgElm);
        Assert.IsTrue(!imgElm.IsSvgImage, "IsSvgImage");

        Bitmap bmp = imgElm.Bitmap;

        Assert.AreEqual(48, bmp.Width);
        Assert.AreEqual(48, bmp.Height);
    }
Exemple #14
0
        private ImageSource GetBitmapSource(SvgImageElement element, WpfDrawingContext context)
        {
            ImageSource imageSource = this.GetBitmap(element, context);

            if (imageSource == null)
            {
                return(imageSource);
            }

            SvgColorProfileElement colorProfile = (SvgColorProfileElement)element.ColorProfile;

            if (colorProfile == null || !(imageSource is BitmapSource))
            {
                return(imageSource);
            }
            else
            {
                BitmapSource         bitmapSource       = (BitmapSource)imageSource;
                BitmapFrame          bitmapSourceFrame  = BitmapFrame.Create(bitmapSource);
                ColorContext         sourceColorContext = null;
                IList <ColorContext> colorContexts      = bitmapSourceFrame.ColorContexts;
                if (colorContexts != null && colorContexts.Count != 0)
                {
                    sourceColorContext = colorContexts[0];
                }
                else
                {
                    sourceColorContext = new ColorContext(bitmapSource.Format);
                    //sourceColorContext = new ColorContext(PixelFormats.Default);
                }

                SvgUriReference svgUri     = colorProfile.UriReference;
                Uri             profileUri = new Uri(svgUri.AbsoluteUri);

                ColorContext         destColorContext = new ColorContext(profileUri);
                ColorConvertedBitmap convertedBitmap  = new ColorConvertedBitmap(bitmapSource,
                                                                                 sourceColorContext, destColorContext, bitmapSource.Format);

                return(convertedBitmap);
            }
        }
        public override BitmapSource Visit(SvgImageElement element,
                                           WpfDrawingContext context)
        {
            string sURI       = element.Href.AnimVal;
            int    nColon     = sURI.IndexOf(":");
            int    nSemiColon = sURI.IndexOf(";");
            int    nComma     = sURI.IndexOf(",");

            string sMimeType = sURI.Substring(nColon + 1, nSemiColon - nColon - 1);

            string sContent = sURI.Substring(nComma + 1);

            byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                            0, sContent.Length);

            //BitmapImage imageSource = new BitmapImage();
            //imageSource.BeginInit();
            //imageSource.StreamSource = new MemoryStream(imageBytes);
            //imageSource.EndInit();

            return(new EmbeddedBitmapSource(new MemoryStream(imageBytes)));
        }
        private ImageSource GetBitmap(SvgImageElement element, WpfDrawingContext context)
        {
            if (element.IsSvgImage)
            {
                return(null);
            }

            if (element.Href == null)
            {
                return(null);
            }

            if (!element.Href.AnimVal.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
            {
                SvgUriReference svgUri      = element.UriReference;
                string          absoluteUri = svgUri.AbsoluteUri;
                if (string.IsNullOrWhiteSpace(absoluteUri))
                {
                    return(null); // most likely, the image does not exist...
                }
                if (absoluteUri.StartsWith("#", StringComparison.OrdinalIgnoreCase))
                {
                    Trace.WriteLine("Uri: " + absoluteUri); // image elements can't reference elements in an svg file
                    return(null);
                }

                Uri imageUri = new Uri(svgUri.AbsoluteUri);
                if (imageUri.IsFile)
                {
                    if (File.Exists(imageUri.LocalPath))
                    {
                        BitmapImage imageSource = new BitmapImage();

                        imageSource.BeginInit();
                        imageSource.CacheOption   = BitmapCacheOption.OnLoad;
                        imageSource.CreateOptions = BitmapCreateOptions.IgnoreImageCache
                                                    | BitmapCreateOptions.PreservePixelFormat;
                        imageSource.UriSource = imageUri;
                        imageSource.EndInit();

//                        imageSource.Freeze();

                        return(imageSource);
                    }

                    return(null);
                }
                else
                {
                    Stream stream = svgUri.ReferencedResource.GetResponseStream();

                    BitmapImage imageSource = new BitmapImage();
                    imageSource.BeginInit();
                    imageSource.CacheOption   = BitmapCacheOption.OnLoad;
                    imageSource.CreateOptions = BitmapCreateOptions.IgnoreImageCache
                                                | BitmapCreateOptions.PreservePixelFormat;
                    imageSource.StreamSource = stream;
                    imageSource.EndInit();

//                    imageSource.Freeze();

                    return(imageSource);
                }
            }
            else
            {
                WpfEmbeddedImageVisitor imageVisitor = context.ImageVisitor;
                if (imageVisitor != null)
                {
                    ImageSource visitorSource = imageVisitor.Visit(element, context);
                    if (visitorSource != null)
                    {
                        return(visitorSource);
                    }
                }

                string sURI       = element.Href.AnimVal.Replace(" ", "");
                int    nColon     = sURI.IndexOf(":", StringComparison.OrdinalIgnoreCase);
                int    nSemiColon = sURI.IndexOf(";", StringComparison.OrdinalIgnoreCase);
                int    nComma     = sURI.IndexOf(",", StringComparison.OrdinalIgnoreCase);

                string sMimeType = sURI.Substring(nColon + 1, nSemiColon - nColon - 1);

                string sContent = sURI.Substring(nComma + 1);
                byte[] bResult  = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                              0, sContent.Length);

                BitmapImage imageSource = new BitmapImage();
                imageSource.BeginInit();
                imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                imageSource.StreamSource  = new MemoryStream(bResult);
                imageSource.EndInit();

//                imageSource.Freeze();

                return(imageSource);
            }
        }
        public static Image GetBitmap(SvgImageElement element)
        {
            var comparer = StringComparison.OrdinalIgnoreCase;

            if (!element.IsSvgImage)
            {
                if (!element.Href.AnimVal.StartsWith("data:", comparer))
                {
                    SvgUriReference svgUri   = element.UriReference;
                    Uri             imageUri = new Uri(svgUri.AbsoluteUri);
                    if (imageUri.IsFile && File.Exists(imageUri.LocalPath))
                    {
                        return(Image.FromFile(imageUri.LocalPath, element.ColorProfile != null));
                    }

                    WebResponse resource = svgUri.ReferencedResource;
                    if (resource == null)
                    {
                        return(null);
                    }

                    Stream stream = resource.GetResponseStream();
                    if (stream == null)
                    {
                        return(null);
                    }

                    return(Image.FromStream(stream, element.ColorProfile != null));
                }

                string sURI = element.Href.AnimVal.Replace(" ", "").Trim();
                sURI = sURI.Replace(@"\n", "");
                int nColon     = sURI.IndexOf(":", comparer);
                int nSemiColon = sURI.IndexOf(";", comparer);
                int nComma     = sURI.IndexOf(",", comparer);

                string sMimeType = sURI.Substring(nColon + 1, nSemiColon - nColon - 1);
                string sContent  = sURI.Substring(nComma + 1);

                sContent = sContent.Replace('-', '+').Replace('_', '/');
                sContent = sContent.PadRight(4 * ((sContent.Length + 3) / 4), '=');
                byte[] bResult = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                             0, sContent.Length);

                if (sMimeType.Equals("image/svg+xml", StringComparison.OrdinalIgnoreCase))
                {
                    GdiGraphicsRenderer renderer = new GdiGraphicsRenderer(true, false);

                    var currentWindow = element.OwnerDocument.Window as SvgWindow;
                    var svgWindow     = currentWindow.CreateOwnedWindow();
                    renderer.Window = svgWindow;

                    SvgDocument doc      = svgWindow.CreateEmptySvgDocument();
                    bool        isGZiped = sContent.StartsWith(GdiObject.GZipSignature, StringComparison.Ordinal);
                    if (isGZiped)
                    {
                        byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                                        0, sContent.Length);
                        using (var stream = new MemoryStream(imageBytes))
                        {
                            using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
                            {
                                doc.Load(zipStream);
                            }
                        }
                    }
                    else
                    {
                        var svgData     = Convert.FromBase64String(Convert.ToBase64String(bResult));
                        var svgFragment = Encoding.ASCII.GetString(svgData);

                        doc.LoadXml(svgFragment);
                    }
                    svgWindow.Document = doc;

                    SvgSvgElement elm = (SvgSvgElement)doc.RootElement;

                    int winWidth  = (int)elm.Width.BaseVal.Value;
                    int winHeight = (int)elm.Height.BaseVal.Value;
                    if (winWidth == 0 || winHeight == 0)
                    {
                        var size = elm.GetSize();
                        winWidth  = (int)size.Width;
                        winHeight = (int)size.Height;
                    }

                    svgWindow.Resize(winWidth, winHeight);

                    renderer.Render(elm as SvgElement);
                    Image img = renderer.RasterImage;

                    return(img);
                }

                MemoryStream ms = new MemoryStream(bResult);
                return(Image.FromStream(ms, element.ColorProfile != null));
            }
            return(null);
        }
Exemple #18
0
        private ImageSource GetImage(SvgImageElement element, WpfDrawingContext context)
        {
            bool   isSavingImages = _saveImages;
            string imagesDir      = _saveDirectory;

            if (context != null && context.Settings.IncludeRuntime == false)
            {
                isSavingImages = true;
                if (string.IsNullOrWhiteSpace(_saveDirectory) ||
                    Directory.Exists(_saveDirectory) == false)
                {
                    var assembly = Assembly.GetExecutingAssembly();
                    if (assembly != null)
                    {
                        imagesDir = PathUtils.Combine(assembly);
                    }
                }
            }

            var comparer = StringComparison.OrdinalIgnoreCase;

            string sURI       = element.Href.AnimVal.Replace(" ", string.Empty);
            int    nColon     = sURI.IndexOf(":", comparer);
            int    nSemiColon = sURI.IndexOf(";", comparer);
            int    nComma     = sURI.IndexOf(",", comparer);

            string sMimeType = sURI.Substring(nColon + 1, nSemiColon - nColon - 1);

            var  sContent   = SvgObject.RemoveWhitespace(sURI.Substring(nComma + 1));
            var  imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(), 0, sContent.Length);
            bool isGZiped   = sContent.StartsWith(SvgConstants.GZipSignature, StringComparison.Ordinal);
            bool isSvgOrXml = sContent.StartsWith(SvgConstants.SvgSignature, StringComparison.Ordinal) ||
                              sContent.StartsWith(SvgConstants.XmlSignature, StringComparison.Ordinal);

            if (string.Equals(sMimeType, "image/svg+xml", comparer) || isSvgOrXml)
            {
                if (isGZiped)
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
                        {
                            using (var reader = new FileSvgReader(context.Settings, true))
                            {
                                return(new DrawingImage(reader.Read(zipStream)));
                            }
                        }
                    }
                }
                else
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (var reader = new FileSvgReader(context.Settings, true))
                        {
                            return(new DrawingImage(reader.Read(stream)));
                        }
                    }
                }
            }

            var memStream = new MemoryStream(imageBytes);

            BitmapImage imageSource = new BitmapImage();

            imageSource.BeginInit();
            imageSource.StreamSource  = memStream;
            imageSource.CacheOption   = BitmapCacheOption.OnLoad;
            imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            imageSource.EndInit();

            string imagePath = null;

            if (isSavingImages && !string.IsNullOrWhiteSpace(imagesDir) && Directory.Exists(imagesDir))
            {
                imagePath = this.GetImagePath(imagesDir);

                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(imageSource));

                using (var fileStream = new FileStream(imagePath, FileMode.Create))
                {
                    encoder.Save(fileStream);
                }

                imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreImageCache;
                imageSource.UriSource     = new Uri(imagePath);

                //imageSource.StreamSource.Dispose();
                //imageSource = null;

                //BitmapImage savedSource = new BitmapImage();

                //savedSource.BeginInit();
                //savedSource.CacheOption   = BitmapCacheOption.None;
                //savedSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreImageCache;
                //savedSource.UriSource = new Uri(imagePath);
                //savedSource.EndInit();

                //savedSource.Freeze();

                //if (_imageCreated != null)
                //{
                //    var eventArgs = new EmbeddedImageSerializerArgs(imagePath, savedSource);
                //    _imageCreated.Invoke(this, eventArgs);
                //}

                //return savedSource;
            }
            else if (_converterFallback)
            {
                //if (_imageCreated != null)
                //{
                //    var eventArgs = new EmbeddedImageSerializerArgs(imagePath, imageSource);
                //    _imageCreated.Invoke(this, eventArgs);
                //}
                return(new EmbeddedBitmapSource(memStream, imageSource));
            }
            if (_imageCreated != null)
            {
                var eventArgs = new EmbeddedImageSerializerArgs(imagePath, imageSource);
                _imageCreated.Invoke(this, eventArgs);
            }

            imageSource.Freeze();

            return(imageSource);
        }
        public override void Render(WpfDrawingRenderer renderer)
        {
            WpfDrawingContext context      = renderer.Context;
            SvgImageElement   imageElement = (SvgImageElement)_svgElement;

            double x      = imageElement.X.AnimVal.Value;
            double y      = imageElement.Y.AnimVal.Value;
            double width  = imageElement.Width.AnimVal.Value;
            double height = imageElement.Height.AnimVal.Value;

            Rect destRect = new Rect(x, y, width, height);
            Rect clipRect = new Rect(x, y, width, height);

            ImageSource imageSource = null;

            if (imageElement.IsSvgImage)
            {
                if (imageElement.IsRootReferenced(imageElement.OwnerDocument.BaseURI))
                {
                    return;
                }

                SvgWindow wnd = GetSvgWindow();
                if (wnd == null)
                {
                    return;
                }
                //_embeddedRenderer.BackColor = Color.Empty;
                _embeddedRenderer.Render(wnd.Document);

                DrawingGroup imageGroup = _embeddedRenderer.Drawing as DrawingGroup;
                if (imageGroup != null &&
                    (imageGroup.Children != null && imageGroup.Children.Count == 1))
                {
                    DrawingGroup imageDrawing = imageGroup.Children[0] as DrawingGroup;
                    if (imageDrawing != null)
                    {
                        imageDrawing.ClipGeometry = null;

                        imageSource = new DrawingImage(imageDrawing);
                    }
                    else
                    {
                        imageGroup.ClipGeometry = null;

                        imageSource = new DrawingImage(imageGroup);
                    }
                }
                else
                {
                    imageSource = new DrawingImage(_embeddedRenderer.Drawing);
                }

                if (_embeddedRenderer != null)
                {
                    _embeddedRenderer.Dispose();
                    _embeddedRenderer = null;
                }
            }
            else
            {
                imageSource = GetBitmapSource(imageElement, context);
            }

            if (imageSource == null)
            {
                return;
            }

            //TODO--PAUL: Set the DecodePixelWidth/DecodePixelHeight?

            // Freeze the DrawingImage for performance benefits.
            //imageSource.Freeze();

            DrawingGroup drawGroup = null;

            ISvgAnimatedPreserveAspectRatio animatedAspectRatio = imageElement.PreserveAspectRatio;

            if (animatedAspectRatio != null && animatedAspectRatio.AnimVal != null)
            {
                SvgPreserveAspectRatio     aspectRatio     = animatedAspectRatio.AnimVal as SvgPreserveAspectRatio;
                SvgPreserveAspectRatioType aspectRatioType =
                    (aspectRatio != null) ? aspectRatio.Align : SvgPreserveAspectRatioType.Unknown;
                if (aspectRatio != null && aspectRatioType != SvgPreserveAspectRatioType.None &&
                    aspectRatioType != SvgPreserveAspectRatioType.Unknown)
                {
                    double imageWidth  = imageSource.Width;
                    double imageHeight = imageSource.Height;

                    double viewWidth  = destRect.Width;
                    double viewHeight = destRect.Height;

                    SvgMeetOrSlice meetOrSlice = aspectRatio.MeetOrSlice;
                    if (meetOrSlice == SvgMeetOrSlice.Meet)
                    {
                        if (imageWidth <= viewWidth && imageHeight <= viewHeight)
                        {
                            if (this.Transform == null)
                            {
                                if (!aspectRatio.IsDefaultAlign) // Cacxa
                                {
                                    destRect = this.GetBounds(destRect, new Size(imageWidth, imageHeight), aspectRatioType);
                                }
                                else
                                {
                                    Transform viewTransform = this.GetAspectRatioTransform(aspectRatio,
                                                                                           new SvgRect(0, 0, imageWidth, imageHeight),
                                                                                           new SvgRect(destRect.X, destRect.Y, destRect.Width, destRect.Height));

                                    if (viewTransform != null)
                                    {
                                        drawGroup           = new DrawingGroup();
                                        drawGroup.Transform = viewTransform;

                                        DrawingGroup lastGroup = context.Peek();
                                        Debug.Assert(lastGroup != null);

                                        if (lastGroup != null)
                                        {
                                            lastGroup.Children.Add(drawGroup);
                                        }

                                        destRect = this.GetBounds(destRect,
                                                                  new Size(imageWidth, imageHeight), aspectRatioType);

                                        // The origin is already handled by the view transform...
                                        destRect.X = 0;
                                        destRect.Y = 0;
                                    }
                                }
                            }
                            else
                            {
                                destRect = new Rect(0, 0, viewWidth, viewHeight);
                            }
                        }
                        else
                        {
                            if (this.Transform == null)
                            {
                                Transform viewTransform = this.GetAspectRatioTransform(aspectRatio,
                                                                                       new SvgRect(0, 0, imageWidth, imageHeight),
                                                                                       new SvgRect(destRect.X, destRect.Y, destRect.Width, destRect.Height));

                                if (viewTransform != null)
                                {
                                    drawGroup           = new DrawingGroup();
                                    drawGroup.Transform = viewTransform;

                                    DrawingGroup lastGroup = context.Peek();
                                    Debug.Assert(lastGroup != null);

                                    if (lastGroup != null)
                                    {
                                        lastGroup.Children.Add(drawGroup);
                                    }

                                    destRect = this.GetBounds(destRect,
                                                              new Size(imageWidth, imageHeight), aspectRatioType);

                                    // The origin is already handled by the view transform...
                                    destRect.X = 0;
                                    destRect.Y = 0;
                                }
                            }
                        }
                    }
                    else if (meetOrSlice == SvgMeetOrSlice.Slice)
                    {
                        var       fScaleX       = viewWidth / imageWidth;
                        var       fScaleY       = viewHeight / imageHeight;
                        Transform viewTransform = this.GetAspectRatioTransform(aspectRatio,
                                                                               new SvgRect(0, 0, imageWidth, imageHeight),
                                                                               new SvgRect(destRect.X, destRect.Y, destRect.Width, destRect.Height));

                        DrawingGroup sliceGroup = new DrawingGroup();
                        sliceGroup.ClipGeometry = new RectangleGeometry(clipRect);

                        DrawingGroup lastGroup = context.Peek();
                        Debug.Assert(lastGroup != null);

                        if (lastGroup != null)
                        {
                            lastGroup.Children.Add(sliceGroup);
                        }

                        if (viewTransform != null)
                        {
                            drawGroup           = new DrawingGroup();
                            drawGroup.Transform = viewTransform;

                            sliceGroup.Children.Add(drawGroup);

                            destRect = this.GetBounds(destRect,
                                                      new Size(imageWidth, imageHeight), aspectRatioType);

                            // The origin is already handled by the view transform...
                            destRect.X = 0;
                            destRect.Y = 0;
                        }
                        else
                        {
                            drawGroup = sliceGroup;
                        }
                    }
                }
            }

            ImageDrawing drawing = new ImageDrawing(imageSource, destRect);

            float opacityValue = -1;

            string opacity = imageElement.GetAttribute("opacity");

            if (string.IsNullOrWhiteSpace(opacity))
            {
                opacity = imageElement.GetPropertyValue("opacity");
            }
            if (!string.IsNullOrWhiteSpace(opacity))
            {
                opacityValue = (float)SvgNumber.ParseNumber(opacity);
                opacityValue = Math.Min(opacityValue, 1);
                opacityValue = Math.Max(opacityValue, 0);
            }

            Geometry  clipGeom  = this.ClipGeometry;
            Transform transform = this.Transform;

            bool ownedGroup = true;

            if (drawGroup == null)
            {
                drawGroup  = context.Peek();
                ownedGroup = false;
            }

            Debug.Assert(drawGroup != null);
            if (drawGroup != null)
            {
                if ((opacityValue >= 0 && opacityValue < 1) || (clipGeom != null && !clipGeom.IsEmpty()) ||
                    (transform != null && !transform.Value.IsIdentity))
                {
                    DrawingGroup clipGroup = ownedGroup ? drawGroup : new DrawingGroup();
                    if (opacityValue >= 0 && opacityValue < 1)
                    {
                        clipGroup.Opacity = opacityValue;
                    }
                    if (clipGeom != null)
                    {
                        SvgUnitType clipUnits = this.ClipUnits;
                        if (clipUnits == SvgUnitType.ObjectBoundingBox)
                        {
                            Rect drawingBounds = drawing.Bounds;

                            TransformGroup transformGroup = new TransformGroup();

                            // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                            transformGroup.Children.Add(
                                new ScaleTransform(drawingBounds.Width, drawingBounds.Height));
                            transformGroup.Children.Add(
                                new TranslateTransform(drawingBounds.X, drawingBounds.Y));

                            clipGeom.Transform = transformGroup;
                        }

                        clipGroup.ClipGeometry = clipGeom;
                    }
                    if (transform != null)
                    {
                        Transform curTransform = clipGroup.Transform;
                        if (curTransform != null && curTransform.Value.IsIdentity == false)
                        {
                            TransformGroup transformGroup = new TransformGroup();
                            transformGroup.Children.Add(curTransform);
                            transformGroup.Children.Add(transform);
                            clipGroup.Transform = transformGroup;
                        }
                        else
                        {
                            clipGroup.Transform = transform;
                        }
                    }

                    clipGroup.Children.Add(drawing);
                    if (!ownedGroup)
                    {
                        drawGroup.Children.Add(clipGroup);
                    }
                }
                else
                {
                    drawGroup.Children.Add(drawing);
                }

                string elementId = this.GetElementName();
                if (ownedGroup)
                {
                    string sVisibility = imageElement.GetPropertyValue("visibility");
                    string sDisplay    = imageElement.GetPropertyValue("display");
                    if (string.Equals(sVisibility, "hidden") || string.Equals(sDisplay, "none"))
                    {
                        drawGroup.Opacity = 0;
                    }

                    if (!_idAssigned && !string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                    {
                        context.RegisterId(elementId);

                        if (context.IncludeRuntime)
                        {
                            SvgObject.SetName(drawGroup, elementId);

                            SvgObject.SetId(drawGroup, elementId);
                        }
                    }

                    // Register this drawing with the Drawing-Document...
                    this.Rendered(drawGroup);
                }
                else if (!_idAssigned)
                {
                    if (!_idAssigned && !string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                    {
                        context.RegisterId(elementId);

                        if (context.IncludeRuntime)
                        {
                            SvgObject.SetName(imageSource, elementId);

                            SvgObject.SetId(imageSource, elementId);
                        }
                    }

                    // Register this drawing with the Drawing-Document...
                    this.Rendered(drawing);
                }
            }
        }
Exemple #20
0
        private BitmapSource GetBitmap(SvgImageElement element, WpfDrawingContext context)
        {
            if (element.IsSvgImage)
            {
                return(null);
            }

            if (!element.Href.AnimVal.StartsWith("data:"))
            {
                SvgUriReference svgUri      = element.UriReference;
                string          absoluteUri = svgUri.AbsoluteUri;
                if (String.IsNullOrEmpty(absoluteUri))
                {
                    return(null); // most likely, the image does not exist...
                }

                Uri imageUri = new Uri(svgUri.AbsoluteUri);
                if (imageUri.IsFile)
                {
                    if (File.Exists(imageUri.LocalPath))
                    {
                        BitmapImage imageSource = new BitmapImage();

                        imageSource.BeginInit();
                        imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                        imageSource.UriSource     = imageUri;
                        imageSource.EndInit();

                        return(imageSource);
                    }

                    return(null);
                }
                else
                {
                    Stream stream = svgUri.ReferencedResource.GetResponseStream();

                    BitmapImage imageSource = new BitmapImage();
                    imageSource.BeginInit();
                    imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                    imageSource.StreamSource  = stream;
                    imageSource.EndInit();

                    return(imageSource);
                }
            }
            else
            {
                WpfEmbeddedImageVisitor imageVisitor = context.ImageVisitor;
                if (imageVisitor != null)
                {
                    BitmapSource visitorSource = imageVisitor.Visit(element, context);
                    if (visitorSource != null)
                    {
                        return(visitorSource);
                    }
                }

                string sURI       = element.Href.AnimVal;
                int    nColon     = sURI.IndexOf(":");
                int    nSemiColon = sURI.IndexOf(";");
                int    nComma     = sURI.IndexOf(",");

                string sMimeType = sURI.Substring(nColon + 1, nSemiColon - nColon - 1);

                string sContent = sURI.Substring(nComma + 1);
                byte[] bResult  = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                              0, sContent.Length);

                BitmapImage imageSource = new BitmapImage();
                imageSource.BeginInit();
                imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                imageSource.StreamSource  = new MemoryStream(bResult);
                imageSource.EndInit();

                return(imageSource);
            }
        }
Exemple #21
0
        private ImageSource GetImage(SvgImageElement element, WpfDrawingContext context)
        {
            bool   isSavingImages = _saveImages;
            string imagesDir      = _saveDirectory;

            if (context != null && context.Settings.IncludeRuntime == false)
            {
                isSavingImages = true;
                if (string.IsNullOrWhiteSpace(_saveDirectory) ||
                    Directory.Exists(_saveDirectory) == false)
                {
                    var assembly = Assembly.GetExecutingAssembly();
                    if (assembly != null)
                    {
                        imagesDir = Path.GetDirectoryName(assembly.Location);
                    }
                }
            }

            var comparer = StringComparison.OrdinalIgnoreCase;

            string sURI       = element.Href.AnimVal.Replace(" ", "");
            int    nColon     = sURI.IndexOf(":", comparer);
            int    nSemiColon = sURI.IndexOf(";", comparer);
            int    nComma     = sURI.IndexOf(",", comparer);

            string sMimeType = sURI.Substring(nColon + 1, nSemiColon - nColon - 1);

            string sContent = SvgObject.RemoveWhitespace(sURI.Substring(nComma + 1));

            byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                            0, sContent.Length);
            bool isGZiped = sContent.StartsWith(SvgObject.GZipSignature, StringComparison.Ordinal);

            if (string.Equals(sMimeType, "image/svg+xml", comparer))
            {
                if (isGZiped)
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
                        {
                            using (var reader = new FileSvgReader(context.Settings))
                                return(new DrawingImage(reader.Read(zipStream)));
                        }
                    }
                }
                else
                {
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (var reader = new FileSvgReader(context.Settings))
                            return(new DrawingImage(reader.Read(stream)));
                    }
                }
            }

            BitmapImage imageSource = new BitmapImage();

            imageSource.BeginInit();
            imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            imageSource.StreamSource  = new MemoryStream(imageBytes);
            imageSource.EndInit();

            imageSource.Freeze();

            if (isSavingImages && !string.IsNullOrWhiteSpace(imagesDir) &&
                Directory.Exists(imagesDir))
            {
                var imagePath = this.GetImagePath(imagesDir);

                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(imageSource));

                using (var fileStream = new FileStream(imagePath, FileMode.Create))
                {
                    encoder.Save(fileStream);
                }

                BitmapImage savedSource = new BitmapImage();

                savedSource.BeginInit();
                savedSource.CacheOption   = BitmapCacheOption.OnLoad;
                savedSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                savedSource.UriSource     = new Uri(imagePath);
                savedSource.EndInit();

                savedSource.Freeze();

                return(savedSource);
            }

            return(imageSource);
        }
Exemple #22
0
        public override void Render(WpfDrawingRenderer renderer)
        {
            WpfDrawingContext context      = renderer.Context;
            SvgImageElement   imageElement = (SvgImageElement)_svgElement;

            double width  = imageElement.Width.AnimVal.Value;
            double height = imageElement.Height.AnimVal.Value;

            Rect destRect = new Rect(imageElement.X.AnimVal.Value, imageElement.Y.AnimVal.Value,
                                     width, height);

            ImageSource imageSource = null;

            if (imageElement.IsSvgImage)
            {
                SvgWindow wnd = GetSvgWindow();
                //_embeddedRenderer.BackColor = Color.Empty;
                _embeddedRenderer.Render(wnd.Document);

                DrawingGroup imageGroup = _embeddedRenderer.Drawing as DrawingGroup;
                if (imageGroup != null &&
                    (imageGroup.Children != null && imageGroup.Children.Count == 1))
                {
                    DrawingGroup drawImage = imageGroup.Children[0] as DrawingGroup;
                    if (drawImage != null)
                    {
                        if (drawImage.ClipGeometry != null)
                        {
                            drawImage.ClipGeometry = null;
                        }

                        imageSource = new DrawingImage(drawImage);
                    }
                    else
                    {
                        if (imageGroup.ClipGeometry != null)
                        {
                            imageGroup.ClipGeometry = null;
                        }

                        imageSource = new DrawingImage(imageGroup);
                    }
                }
                else
                {
                    imageSource = new DrawingImage(_embeddedRenderer.Drawing);
                }

                if (_embeddedRenderer != null)
                {
                    _embeddedRenderer.Dispose();
                    _embeddedRenderer = null;
                }
            }
            else
            {
                imageSource = GetBitmapSource(imageElement, context);
            }

            if (imageSource == null)
            {
                return;
            }

            //TODO--PAUL: Set the DecodePixelWidth/DecodePixelHeight?

            // Freeze the DrawingImage for performance benefits.
            imageSource.Freeze();

            DrawingGroup drawGroup = null;

            ISvgAnimatedPreserveAspectRatio animatedAspectRatio = imageElement.PreserveAspectRatio;

            if (animatedAspectRatio != null && animatedAspectRatio.AnimVal != null)
            {
                SvgPreserveAspectRatio     aspectRatio     = animatedAspectRatio.AnimVal as SvgPreserveAspectRatio;
                SvgPreserveAspectRatioType aspectRatioType =
                    (aspectRatio != null) ? aspectRatio.Align : SvgPreserveAspectRatioType.Unknown;
                if (aspectRatio != null && aspectRatioType != SvgPreserveAspectRatioType.None &&
                    aspectRatioType != SvgPreserveAspectRatioType.Unknown)
                {
                    double imageWidth  = imageSource.Width;
                    double imageHeight = imageSource.Height;

                    double viewWidth  = destRect.Width;
                    double viewHeight = destRect.Height;

                    SvgMeetOrSlice meetOrSlice = aspectRatio.MeetOrSlice;
                    if (meetOrSlice == SvgMeetOrSlice.Meet)
                    {
                        if (imageWidth <= viewWidth && imageHeight <= viewHeight)
                        {
                            destRect = this.GetBounds(destRect,
                                                      new Size(imageWidth, imageHeight), aspectRatioType);
                        }
                        else
                        {
                            Transform viewTransform = this.GetAspectRatioTransform(aspectRatio,
                                                                                   new SvgRect(0, 0, imageWidth, imageHeight),
                                                                                   new SvgRect(destRect.X, destRect.Y, destRect.Width, destRect.Height));
                            //Transform scaleTransform = this.FitToViewbox(aspectRatio,
                            //  new SvgRect(destRect.X, destRect.Y, imageWidth, imageHeight),
                            //  new SvgRect(destRect.X, destRect.Y, destRect.Width, destRect.Height));

                            if (viewTransform != null)
                            {
                                drawGroup           = new DrawingGroup();
                                drawGroup.Transform = viewTransform;

                                DrawingGroup lastGroup = context.Peek();
                                Debug.Assert(lastGroup != null);

                                if (lastGroup != null)
                                {
                                    lastGroup.Children.Add(drawGroup);
                                }

                                destRect = this.GetBounds(destRect,
                                                          new Size(imageWidth, imageHeight), aspectRatioType);

                                // The origin is already handled by the view transform...
                                destRect.X = 0;
                                destRect.Y = 0;
                            }
                        }
                    }
                    else if (meetOrSlice == SvgMeetOrSlice.Slice)
                    {
                    }
                }
            }

            ImageDrawing drawing = new ImageDrawing(imageSource, destRect);

            float opacityValue = -1;

            string opacity = imageElement.GetAttribute("opacity");

            if (opacity != null && opacity.Length > 0)
            {
                opacityValue = (float)SvgNumber.ParseNumber(opacity);
                opacityValue = Math.Min(opacityValue, 1);
                opacityValue = Math.Max(opacityValue, 0);
            }

            Geometry  clipGeom  = this.ClipGeometry;
            Transform transform = this.Transform;

            if (drawGroup == null)
            {
                drawGroup = context.Peek();
            }
            Debug.Assert(drawGroup != null);
            if (drawGroup != null)
            {
                if (opacityValue >= 0 || (clipGeom != null && !clipGeom.IsEmpty()) ||
                    (transform != null && !transform.Value.IsIdentity))
                {
                    DrawingGroup clipGroup = new DrawingGroup();
                    if (opacityValue >= 0)
                    {
                        clipGroup.Opacity = opacityValue;
                    }
                    if (clipGeom != null)
                    {
                        SvgUnitType clipUnits = this.ClipUnits;
                        if (clipUnits == SvgUnitType.ObjectBoundingBox)
                        {
                            Rect drawingBounds = drawing.Bounds;

                            TransformGroup transformGroup = new TransformGroup();

                            // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                            transformGroup.Children.Add(
                                new ScaleTransform(drawingBounds.Width, drawingBounds.Height));
                            transformGroup.Children.Add(
                                new TranslateTransform(drawingBounds.X, drawingBounds.Y));

                            clipGeom.Transform = transformGroup;
                        }

                        clipGroup.ClipGeometry = clipGeom;
                    }
                    if (transform != null)
                    {
                        clipGroup.Transform = transform;
                    }

                    clipGroup.Children.Add(drawing);
                    drawGroup.Children.Add(clipGroup);
                }
                else
                {
                    drawGroup.Children.Add(drawing);
                }
            }
        }
Exemple #23
0
 public abstract BitmapSource Visit(SvgImageElement element,
                                    WpfDrawingContext context);
Exemple #24
0
        public override void Render(GdiGraphicsRenderer renderer)
        {
            var             graphics = renderer.GdiGraphics;
            SvgImageElement iElement = (SvgImageElement)_svgElement;

            ImageAttributes imageAttributes = new ImageAttributes();

            string sOpacity = iElement.GetPropertyValue("opacity");

            if (sOpacity != null && sOpacity.Length > 0)
            {
                double      opacity       = SvgNumber.ParseNumber(sOpacity);
                ColorMatrix myColorMatrix = new ColorMatrix();
                myColorMatrix.Matrix00 = 1.00f;                 // Red
                myColorMatrix.Matrix11 = 1.00f;                 // Green
                myColorMatrix.Matrix22 = 1.00f;                 // Blue
                myColorMatrix.Matrix33 = (float)opacity;        // alpha
                myColorMatrix.Matrix44 = 1.00f;                 // w

                imageAttributes.SetColorMatrix(myColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            }

            float width  = (float)iElement.Width.AnimVal.Value;
            float height = (float)iElement.Height.AnimVal.Value;

            RectangleF destRect = new RectangleF((float)iElement.X.AnimVal.Value,
                                                 (float)iElement.Y.AnimVal.Value, (float)iElement.Width.AnimVal.Value,
                                                 (float)iElement.Height.AnimVal.Value);

            Image image = null;

            if (iElement.IsSvgImage)
            {
                SvgWindow wnd = GetSvgWindow();
                _embeddedRenderer.BackColor = Color.Empty;
                _embeddedRenderer.Render(wnd.Document);

                image = _embeddedRenderer.RasterImage;
            }
            else
            {
                image = GetBitmap(iElement);
            }

            if (image != null)
            {
                // code extracted from FitToViewbox
                var spar = (SvgPreserveAspectRatio)iElement.PreserveAspectRatio.AnimVal ?? new SvgPreserveAspectRatio("none", iElement);

                double[] translateAndScale = spar.FitToViewBox(new SvgRect(0, 0, image.Width, image.Height),
                                                               new SvgRect(destRect.X, destRect.Y, destRect.Width, destRect.Height));
                graphics.TranslateTransform((float)translateAndScale[0], (float)translateAndScale[1]);
                graphics.ScaleTransform((float)translateAndScale[2], (float)translateAndScale[3]);
                graphics.DrawImage(this, image, new Rectangle(0, 0, image.Width, image.Height), 0f, 0f,
                                   image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes);

                image.Dispose();
                image = null;
            }

            if (_embeddedRenderer != null)
            {
                _embeddedRenderer.Dispose();
                _embeddedRenderer = null;
            }

            if (imageAttributes != null)
            {
                imageAttributes.Dispose();
                imageAttributes = null;
            }
        }
Exemple #25
0
        public override void Render(GdiGraphicsRenderer renderer)
        {
            GdiGraphicsWrapper graphics = renderer.GraphicsWrapper;
            SvgImageElement    iElement = (SvgImageElement)element;

            ImageAttributes imageAttributes = new ImageAttributes();

            string sOpacity = iElement.GetPropertyValue("opacity");

            if (sOpacity != null && sOpacity.Length > 0)
            {
                double      opacity       = SvgNumber.ParseNumber(sOpacity);
                ColorMatrix myColorMatrix = new ColorMatrix();
                myColorMatrix.Matrix00 = 1.00f;                 // Red
                myColorMatrix.Matrix11 = 1.00f;                 // Green
                myColorMatrix.Matrix22 = 1.00f;                 // Blue
                myColorMatrix.Matrix33 = (float)opacity;        // alpha
                myColorMatrix.Matrix44 = 1.00f;                 // w

                imageAttributes.SetColorMatrix(myColorMatrix,
                                               ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            }

            float width  = (float)iElement.Width.AnimVal.Value;
            float height = (float)iElement.Height.AnimVal.Value;

            Rectangle destRect = new Rectangle(Convert.ToInt32(iElement.X.AnimVal.Value),
                                               Convert.ToInt32(iElement.Y.AnimVal.Value),
                                               Convert.ToInt32(width), Convert.ToInt32(height));

            Image image = null;

            if (iElement.IsSvgImage)
            {
                SvgWindow wnd = GetSvgWindow();
                _embeddedRenderer.BackColor = Color.Empty;
                _embeddedRenderer.Render(wnd.Document);

                image = _embeddedRenderer.RasterImage;
            }
            else
            {
                image = GetBitmap(iElement);
            }

            if (image != null)
            {
                graphics.DrawImage(this, image, destRect, 0f, 0f,
                                   image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes);

                image.Dispose();
                image = null;
            }

            if (_embeddedRenderer != null)
            {
                _embeddedRenderer.Dispose();
                _embeddedRenderer = null;
            }

            if (imageAttributes != null)
            {
                imageAttributes.Dispose();
                imageAttributes = null;
            }
        }
        public override void Render(GdiGraphicsRenderer renderer)
        {
            base.Render(renderer);

            var             graphics = renderer.GdiGraphics;
            SvgImageElement iElement = (SvgImageElement)_svgElement;

            ImageAttributes imageAttributes = new ImageAttributes();

            float opacityValue = -1;

            string opacity = iElement.GetAttribute("opacity");

            if (string.IsNullOrWhiteSpace(opacity))
            {
                opacity = iElement.GetPropertyValue("opacity");
            }
            if (!string.IsNullOrWhiteSpace(opacity))
            {
                opacityValue = (float)SvgNumber.ParseNumber(opacity);
                opacityValue = Math.Min(opacityValue, 1);
                opacityValue = Math.Max(opacityValue, 0);
            }

            if (opacityValue >= 0 && opacityValue < 1)
            {
                ColorMatrix colorMatrix = new ColorMatrix();
                colorMatrix.Matrix00 = 1.00f;                 // Red
                colorMatrix.Matrix11 = 1.00f;                 // Green
                colorMatrix.Matrix22 = 1.00f;                 // Blue
                colorMatrix.Matrix33 = opacityValue;          // alpha
                colorMatrix.Matrix44 = 1.00f;                 // w

                imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            }

            float width  = (float)iElement.Width.AnimVal.Value;
            float height = (float)iElement.Height.AnimVal.Value;

            RectangleF destRect = new RectangleF((float)iElement.X.AnimVal.Value,
                                                 (float)iElement.Y.AnimVal.Value, (float)iElement.Width.AnimVal.Value,
                                                 (float)iElement.Height.AnimVal.Value);

            RectangleF srcRect;
            RectangleF clipRect = destRect;

//            var container = graphics.BeginContainer();
            graphics.SetClip(new Region(clipRect), CombineMode.Intersect);

            Image     image  = null;
            SvgWindow svgWnd = null;

            if (iElement.IsSvgImage)
            {
                svgWnd = GetSvgWindow(graphics);
                if (width > 0 && height > 0)
                {
                    srcRect = new RectangleF(0, 0, width, height);
                }
                else
                {
                    SvgSvgElement svgEl = (SvgSvgElement)svgWnd.Document.RootElement;

                    SvgSizeF size = svgEl.GetSize();

                    srcRect = new RectangleF(new PointF(0, 0), new SizeF(size.Width, size.Height));
                }
            }
            else
            {
                image = GetBitmap(iElement);
                if (image == null)
                {
                    return;
                }
                srcRect = new RectangleF(0, 0, image.Width, image.Height);
            }

            ISvgAnimatedPreserveAspectRatio animatedAspectRatio = iElement.PreserveAspectRatio;

            if (animatedAspectRatio != null && animatedAspectRatio.AnimVal != null)
            {
                SvgPreserveAspectRatio     aspectRatio     = animatedAspectRatio.AnimVal as SvgPreserveAspectRatio;
                SvgPreserveAspectRatioType aspectRatioType =
                    (aspectRatio != null) ? aspectRatio.Align : SvgPreserveAspectRatioType.Unknown;

                if (aspectRatio != null && aspectRatioType != SvgPreserveAspectRatioType.None &&
                    aspectRatioType != SvgPreserveAspectRatioType.Unknown)
                {
                    var fScaleX = destRect.Width / srcRect.Width;
                    var fScaleY = destRect.Height / srcRect.Height;
                    var xOffset = 0.0f;
                    var yOffset = 0.0f;

                    SvgMeetOrSlice meetOrSlice = aspectRatio.MeetOrSlice;
                    if (meetOrSlice == SvgMeetOrSlice.Slice)
                    {
                        fScaleX = Math.Max(fScaleX, fScaleY);
                        fScaleY = Math.Max(fScaleX, fScaleY);
                    }
                    else
                    {
                        fScaleX = Math.Min(fScaleX, fScaleY);
                        fScaleY = Math.Min(fScaleX, fScaleY);
                    }

                    switch (aspectRatioType)
                    {
                    case SvgPreserveAspectRatioType.XMinYMin:
                        break;

                    case SvgPreserveAspectRatioType.XMidYMin:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX) / 2;
                        break;

                    case SvgPreserveAspectRatioType.XMaxYMin:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX);
                        break;

                    case SvgPreserveAspectRatioType.XMinYMid:
                        yOffset = (destRect.Height - srcRect.Height * fScaleY) / 2;
                        break;

                    case SvgPreserveAspectRatioType.XMidYMid:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX) / 2;
                        yOffset = (destRect.Height - srcRect.Height * fScaleY) / 2;
                        break;

                    case SvgPreserveAspectRatioType.XMaxYMid:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX);
                        yOffset = (destRect.Height - srcRect.Height * fScaleY) / 2;
                        break;

                    case SvgPreserveAspectRatioType.XMinYMax:
                        yOffset = (destRect.Height - srcRect.Height * fScaleY);
                        break;

                    case SvgPreserveAspectRatioType.XMidYMax:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX) / 2;
                        yOffset = (destRect.Height - srcRect.Height * fScaleY);
                        break;

                    case SvgPreserveAspectRatioType.XMaxYMax:
                        xOffset = (destRect.Width - srcRect.Width * fScaleX);
                        yOffset = (destRect.Height - srcRect.Height * fScaleY);
                        break;
                    }

                    destRect = new RectangleF(destRect.X + xOffset, destRect.Y + yOffset,
                                              srcRect.Width * fScaleX, srcRect.Height * fScaleY);
                }
                if (image != null)
                {
                    SvgColorProfileElement colorProfile = (SvgColorProfileElement)iElement.ColorProfile;
                    if (colorProfile != null)
                    {
                        SvgUriReference svgUri     = colorProfile.UriReference;
                        Uri             profileUri = new Uri(svgUri.AbsoluteUri);

                        imageAttributes.SetOutputChannelColorProfile(profileUri.LocalPath, ColorAdjustType.Default);
                    }

                    graphics.DrawImage(this, image, destRect, srcRect, GraphicsUnit.Pixel, imageAttributes);

                    image.Dispose();
                    image = null;
                }
                else if (iElement.IsSvgImage && svgWnd != null)
                {
                    svgWnd.Resize((int)srcRect.Width, (int)srcRect.Height);

                    var currOffset = new PointF(graphics.Transform.OffsetX, graphics.Transform.OffsetY);
                    if (!currOffset.IsEmpty)
                    {
                        graphics.TranslateTransform(-currOffset.X, -currOffset.Y);
                    }
                    graphics.ScaleTransform(destRect.Width / srcRect.Width, destRect.Height / srcRect.Height);
                    if (!currOffset.IsEmpty)
                    {
                        graphics.TranslateTransform(currOffset.X + destRect.X, currOffset.Y + destRect.Y);
                    }

                    _embeddedRenderer.Render(svgWnd.Document);
                }

                graphics.ResetClip();
//                graphics.EndContainer(container);
            }

            if (_embeddedRenderer != null)
            {
                _embeddedRenderer.GdiGraphics = null;
                _embeddedRenderer.Dispose();
                _embeddedRenderer = null;
            }

            if (imageAttributes != null)
            {
                imageAttributes.Dispose();
                imageAttributes = null;
            }
        }