示例#1
0
        private void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            // 1. Create conversion options
            WpfDrawingSettings settings = new WpfDrawingSettings();
            settings.IncludeRuntime = true;
            settings.TextAsGeometry = false;

            // 2. Select a file to be converted
            string svgTestFile = "Test.svg";

            // 3. Create a file reader
            FileSvgReader converter = new FileSvgReader(settings);
            // 4. Read the SVG file
            DrawingGroup drawing = converter.Read(svgTestFile);

            if (drawing != null)
            {
                svgImage.Source = new DrawingImage(drawing);

                using (StringWriter textWriter = new StringWriter())
                {
                    if (converter.Save(textWriter))
                    {
                        svgBox.Text = textWriter.ToString();
                    }
                }

            }
        }
示例#2
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)));
            }
        }
示例#3
0
        private void OnWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            ConsoleWorker worker = (ConsoleWorker)sender;

            ConverterOptions options = this.Options;

            _wpfSettings.IncludeRuntime = options.IncludeRuntime;
            _wpfSettings.TextAsGeometry = options.TextAsGeometry;

            _fileReader.UseFrameXamlWriter = !options.UseCustomXamlWriter;

            if (options.GeneralWpf)
            {
                _fileReader.SaveXaml = options.SaveXaml;
                _fileReader.SaveZaml = options.SaveZaml;
            }
            else
            {
                _fileReader.SaveXaml = false;
                _fileReader.SaveZaml = false;
            }

            _drawing = _fileReader.Read(_sourceFile, _outputInfoDir);

            if (_drawing == null)
            {
                e.Result = "Failed";
                return;
            }

            if (options.GenerateImage)
            {
                _fileReader.SaveImage(_sourceFile, _outputInfoDir,
                                      options.EncoderType);

                _imageFile = _fileReader.ImageFile;
            }
            _xamlFile = _fileReader.XamlFile;
            _zamlFile = _fileReader.ZamlFile;

            if (_drawing.CanFreeze)
            {
                _drawing.Freeze();
            }

            e.Result = "Successful";
        }
        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)));
        }
示例#5
0
        /// <summary>
        /// Performs the conversion of a valid SVG source stream to the <see cref="DrawingGroup"/>.
        /// </summary>
        /// <param name="svgStream">A stream providing access to the SVG source data.</param>
        /// <param name="settings">
        /// This specifies the settings used by the rendering or drawing engine.
        /// If this is <see langword="null"/>, the default settings is used.
        /// </param>
        /// <returns>
        /// This returns <see cref="DrawingGroup"/> if successful; otherwise, it
        /// returns <see langword="null"/>.
        /// </returns>
        protected virtual DrawingGroup CreateDrawing(Stream svgStream, WpfDrawingSettings settings)
        {
            if (svgStream == null)
            {
                return(null);
            }

            DrawingGroup drawing = null;

            using (FileSvgReader reader = new FileSvgReader(settings))
            {
                drawing = reader.Read(svgStream);
            }

            return(drawing);
        }
		private void OnSelectPicture()
		{
			var openFileDialog = new OpenFileDialog();
			openFileDialog.Filter = "Все файлы изображений|*.bmp; *.png; *.jpeg; *.jpg; *.svg|BMP Файлы|*.bmp|PNG Файлы|*.png|JPEG Файлы|*.jpeg|JPG Файлы|*.jpg|SVG Файлы|*.svg";
			if (openFileDialog.ShowDialog().Value)
			{
				// TODO: ограничить размер файла
				_newImage = true;
				_sourceName = openFileDialog.FileName;
				_imageSource = null;
				_isVectorImage = VectorGraphicExtensions.Contains(Path.GetExtension(_sourceName));
				if (_isVectorImage)
				{
					using (FileSvgReader reader = new FileSvgReader(_settings))
						_drawing = reader.Read(_sourceName);
					_drawing.Freeze();
				}
				UpdateImage();
			}
		}
		private void OnSelectPicture()
		{
			var openFileDialog = new OpenFileDialog();
			openFileDialog.Filter = "Все файлы изображений|*.bmp; *.png; *.jpeg; *.jpg; *.svg|BMP Файлы|*.bmp|PNG Файлы|*.png|JPEG Файлы|*.jpeg|JPG Файлы|*.jpg|SVG Файлы|*.svg";
			if (openFileDialog.ShowDialog().Value)
			{
				_sourceName = openFileDialog.FileName;
				if (VectorGraphicExtensions.Contains(Path.GetExtension(_sourceName)))
				{
					using (FileSvgReader reader = new FileSvgReader(_settings))
						_drawing = reader.Read(openFileDialog.FileName);
					ImageSource = new DrawingImage(_drawing);
				}
				else
				{
					_drawing = null;
					ImageSource = new BitmapImage(new Uri(_sourceName));
				}
				_imageChanged = true;
			}
		}
        public static async Task<DrawingImage> Retrieve(DcrGraph graph)
        {
            var body = "src=" + graph.ExportToXml();

            var tempFilePath = Path.Combine(Path.GetTempPath(), "SaveFile.svg");

            using (WebClient wc = new WebClient()) 
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

                //var encodedBody = SharpVectors.HttpUtility.UrlEncode(body);
                //if (encodedBody == null)
                //{
                //    return null;
                //}
                    
                var encodedBody = Regex.Replace(body, @"[^\w\s<>/""=]", "");
                //var encodedBody = body.Replace(" & ", "and"); // TODO: Replace all illegal characters...?
                if (encodedBody.Contains("_")) encodedBody = encodedBody.Replace("_", "");

                var result = await wc.UploadStringTaskAsync("http://dcr.itu.dk:8023/trace/dcr", encodedBody);
                    
                //TODO: don't save it as a file
                System.IO.File.WriteAllText(tempFilePath, result);
                    
            }


            //conversion options
            WpfDrawingSettings settings = new WpfDrawingSettings();
            settings.IncludeRuntime = true;
            settings.TextAsGeometry = true;

            FileSvgReader converter = new FileSvgReader(settings);

            var xamlFile = converter.Read(tempFilePath);


            return new DrawingImage(xamlFile);
        }
示例#9
0
        /// <summary>
        /// Performs the conversion of a valid SVG source file to the <see cref="DrawingGroup"/>.
        /// </summary>
        /// <param name="svgSource">A <see cref="Uri"/> defining the path to the SVG source.</param>
        /// <param name="settings">
        /// This specifies the settings used by the rendering or drawing engine.
        /// If this is <see langword="null"/>, the default settings is used.
        /// </param>
        /// <returns>
        /// This returns <see cref="DrawingGroup"/> if successful; otherwise, it
        /// returns <see langword="null"/>.
        /// </returns>
        protected virtual DrawingGroup CreateDrawing(Uri svgSource, WpfDrawingSettings settings)
        {
            if (svgSource == null)
            {
                return(null);
            }

            string scheme = svgSource.Scheme;

            if (string.IsNullOrWhiteSpace(scheme))
            {
                return(null);
            }

            var comparer = StringComparison.OrdinalIgnoreCase;

            DrawingGroup drawing = null;

            switch (scheme)
            {
            case "file":
            //case "ftp":
            case "https":
            case "http":
                using (FileSvgReader reader = new FileSvgReader(settings))
                {
                    drawing = reader.Read(svgSource);
                }
                break;

            case "pack":
                StreamResourceInfo svgStreamInfo = null;
                if (svgSource.ToString().IndexOf("siteoforigin", comparer) >= 0)
                {
                    svgStreamInfo = Application.GetRemoteStream(svgSource);
                }
                else
                {
                    svgStreamInfo = Application.GetResourceStream(svgSource);
                }

                Stream svgStream = (svgStreamInfo != null) ? svgStreamInfo.Stream : null;

                if (svgStream != null)
                {
                    string fileExt      = Path.GetExtension(svgSource.ToString());
                    bool   isCompressed = !string.IsNullOrWhiteSpace(fileExt) &&
                                          string.Equals(fileExt, ".svgz", comparer);

                    if (isCompressed)
                    {
                        using (svgStream)
                        {
                            using (GZipStream zipStream = new GZipStream(svgStream, CompressionMode.Decompress))
                            {
                                using (FileSvgReader reader = new FileSvgReader(settings))
                                {
                                    drawing = reader.Read(zipStream);
                                }
                            }
                        }
                    }
                    else
                    {
                        using (svgStream)
                        {
                            using (FileSvgReader reader = new FileSvgReader(settings))
                            {
                                drawing = reader.Read(svgStream);
                            }
                        }
                    }
                }
                break;

            case "data":
                var sourceData = svgSource.OriginalString.Replace(" ", "");

                int nColon     = sourceData.IndexOf(":", comparer);
                int nSemiColon = sourceData.IndexOf(";", comparer);
                int nComma     = sourceData.IndexOf(",", comparer);

                string sMimeType = sourceData.Substring(nColon + 1, nSemiColon - nColon - 1);
                string sEncoding = sourceData.Substring(nSemiColon + 1, nComma - nSemiColon - 1);

                if (string.Equals(sMimeType.Trim(), "image/svg+xml", comparer) &&
                    string.Equals(sEncoding.Trim(), "base64", comparer))
                {
                    string sContent   = SvgObject.RemoveWhitespace(sourceData.Substring(nComma + 1));
                    byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                                    0, sContent.Length);
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (var reader = new FileSvgReader(settings))
                        {
                            drawing = reader.Read(stream);
                        }
                    }
                }
                break;
            }

            return(drawing);
        }
 /// <summary>
 /// Background task work method.
 /// </summary>
 private void DoPrepareSvg(object sender, DoWorkEventArgs e)
 {
     // Lock to allow only one of these operations at a time.
     lock (_updateLock)
     {
         KanjiDao dao = new KanjiDao();
         // Get the kanji strokes.
         KanjiStrokes strokes = dao.GetKanjiStrokes(_kanjiEntity.DbKanji.ID);
         if (strokes != null && strokes.FramesSvg.Length > 0)
         {
             // If the strokes was successfuly retrieved, we have to read the compressed SVG contained inside.
             SharpVectors.Renderers.Wpf.WpfDrawingSettings settings = new SharpVectors.Renderers.Wpf.WpfDrawingSettings();
             using (FileSvgReader r = new FileSvgReader(settings))
             {
                 // Unzip the stream and remove instances of "px" that are problematic for SharpVectors.
                 string svgString = StringCompressionHelper.Unzip(strokes.FramesSvg);
                 svgString = svgString.Replace("px", string.Empty);
                 StrokesCount = Regex.Matches(svgString, "<circle").Count;
                 using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(svgString)))
                 {
                     // Then read the stream to a DrawingGroup.
                     // We are forced to do this operation on the UI thread because DrawingGroups must
                     // be always manipulated by the same thread.
                     DispatcherHelper.Invoke(() => 
                         {
                             StrokesDrawingGroup = r.Read(stream);
                             SetCurrentStroke(1);
                         });
                 }
             }
         }
     }
 }
示例#11
0
        private void ConvertFiles(DoWorkEventArgs e, DirectoryInfo target)
        {
            _fileReader.FallbackOnWriterError = _fallbackOnWriterError;

            if (e.Cancel)
            {
                return;
            }

            if (_worker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            DirectoryInfo outputDir = target;

            foreach (string svgFileName in _sourceFiles)
            {
                if (_worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                string fileExt = Path.GetExtension(svgFileName);
                if (String.Equals(fileExt, ".svg", StringComparison.OrdinalIgnoreCase) ||
                    String.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        if (_worker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }

                        if (target == null)
                        {
                            outputDir = new DirectoryInfo(
                                Path.GetDirectoryName(svgFileName));
                        }

                        DrawingGroup drawing = _fileReader.Read(svgFileName,
                                                                outputDir);

                        if (drawing == null)
                        {
                            if (_continueOnError)
                            {
                                throw new InvalidOperationException(
                                          "The conversion failed due to unknown error.");
                            }
                        }

                        if (drawing != null && _options.GenerateImage)
                        {
                            _fileReader.SaveImage(svgFileName, target,
                                                  _options.EncoderType);
                        }

                        if (drawing != null)
                        {
                            _convertedCount++;
                        }

                        if (_fileReader.WriterErrorOccurred)
                        {
                            _writerErrorOccurred = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        _errorFiles.Add(svgFileName);

                        if (_continueOnError)
                        {
                            StringBuilder builder = new StringBuilder();
                            builder.AppendLine("Error converting: " + svgFileName);
                            builder.AppendFormat("Error: Exception ({0})", ex.GetType());
                            builder.AppendLine();
                            builder.AppendLine(ex.Message);
                            builder.AppendLine(ex.ToString());

                            _worker.ReportProgress(0, builder.ToString());
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
        }
示例#12
0
        /// <summary>
        /// This converts the SVG resource specified by the Uri to <see cref="DrawingGroup"/>.
        /// </summary>
        /// <param name="svgSource">A <see cref="Uri"/> specifying the source of the SVG resource.</param>
        /// <returns>A <see cref="DrawingGroup"/> of the converted SVG resource.</returns>
        protected virtual DrawingGroup GetDrawing(Uri svgSource)
        {
            string scheme = null;
            // A little hack to display preview in design mode: The design mode Uri is not absolute.
            bool designTime = DesignerProperties.GetIsInDesignMode(new DependencyObject());

            if (designTime && svgSource.IsAbsoluteUri == false)
            {
                scheme = "pack";
            }
            else
            {
                scheme = svgSource.Scheme;
            }
            if (string.IsNullOrWhiteSpace(scheme))
            {
                return(null);
            }

            WpfDrawingSettings settings = new WpfDrawingSettings();

            settings.IncludeRuntime = _includeRuntime;
            settings.TextAsGeometry = _textAsGeometry;
            settings.OptimizePath   = _optimizePath;
            if (_culture != null)
            {
                settings.CultureInfo = _culture;
            }

            switch (scheme)
            {
            case "file":
            //case "ftp":
            case "https":
            case "http":
                using (FileSvgReader reader = new FileSvgReader(settings))
                {
                    DrawingGroup drawGroup = reader.Read(svgSource);

                    if (drawGroup != null)
                    {
                        return(drawGroup);
                    }
                }
                break;

            case "pack":
                StreamResourceInfo svgStreamInfo = null;
                if (svgSource.ToString().IndexOf("siteoforigin", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    svgStreamInfo = Application.GetRemoteStream(svgSource);
                }
                else
                {
                    svgStreamInfo = Application.GetResourceStream(svgSource);
                }

                Stream svgStream = (svgStreamInfo != null) ? svgStreamInfo.Stream : null;

                if (svgStream != null)
                {
                    string fileExt      = Path.GetExtension(svgSource.ToString());
                    bool   isCompressed = !string.IsNullOrWhiteSpace(fileExt) &&
                                          string.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase);

                    if (isCompressed)
                    {
                        using (svgStream)
                        {
                            using (var zipStream = new GZipStream(svgStream, CompressionMode.Decompress))
                            {
                                using (FileSvgReader reader = new FileSvgReader(settings))
                                {
                                    DrawingGroup drawGroup = reader.Read(zipStream);

                                    if (drawGroup != null)
                                    {
                                        return(drawGroup);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        using (svgStream)
                        {
                            using (FileSvgReader reader = new FileSvgReader(settings))
                            {
                                DrawingGroup drawGroup = reader.Read(svgStream);

                                if (drawGroup != null)
                                {
                                    return(drawGroup);
                                }
                            }
                        }
                    }
                }
                break;

            case "data":
                var sourceData = svgSource.OriginalString.Replace(" ", "");

                int nColon     = sourceData.IndexOf(":", StringComparison.OrdinalIgnoreCase);
                int nSemiColon = sourceData.IndexOf(";", StringComparison.OrdinalIgnoreCase);
                int nComma     = sourceData.IndexOf(",", StringComparison.OrdinalIgnoreCase);

                string sMimeType = sourceData.Substring(nColon + 1, nSemiColon - nColon - 1);
                string sEncoding = sourceData.Substring(nSemiColon + 1, nComma - nSemiColon - 1);

                if (string.Equals(sMimeType.Trim(), "image/svg+xml", StringComparison.OrdinalIgnoreCase) &&
                    string.Equals(sEncoding.Trim(), "base64", StringComparison.OrdinalIgnoreCase))
                {
                    string sContent   = SvgObject.RemoveWhitespace(sourceData.Substring(nComma + 1));
                    byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                                    0, sContent.Length);
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        using (var reader = new FileSvgReader(settings))
                        {
                            DrawingGroup drawGroup = reader.Read(stream);
                            if (drawGroup != null)
                            {
                                return(drawGroup);
                            }
                        }
                    }
                }
                break;
            }

            return(null);
        }
示例#13
0
        private void ConvertFiles(DoWorkEventArgs e, DirectoryInfo source,
                                  DirectoryInfo target)
        {
            _fileReader.FallbackOnWriterError = _fallbackOnWriterError;

            if (e.Cancel)
            {
                return;
            }

            if (_worker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            ConverterOptions options = this.Options;

            IEnumerable <string> fileIterator = DirectoryUtils.FindFiles(
                source, "*.*", SearchOption.TopDirectoryOnly);

            foreach (string svgFileName in fileIterator)
            {
                if (_worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                string fileExt = Path.GetExtension(svgFileName);
                if (string.Equals(fileExt, ".svg", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        FileAttributes fileAttr = File.GetAttributes(svgFileName);
                        if (!_includeHidden)
                        {
                            if ((fileAttr & FileAttributes.Hidden) == FileAttributes.Hidden)
                            {
                                continue;
                            }
                        }

                        FileSecurity security = null;

                        if (_includeSecurity)
                        {
                            security = File.GetAccessControl(svgFileName);
                        }

                        if (_worker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }

                        DrawingGroup drawing = _fileReader.Read(svgFileName,
                                                                target);

                        if (drawing == null)
                        {
                            if (_continueOnError)
                            {
                                throw new InvalidOperationException(
                                          "The conversion failed due to unknown error.");
                            }
                        }

                        if (options.SaveXaml)
                        {
                            string xamlFile = _fileReader.XamlFile;
                            if (!string.IsNullOrWhiteSpace(xamlFile) &&
                                File.Exists(xamlFile))
                            {
                                File.SetAttributes(xamlFile, fileAttr);

                                // if required to set the security or access control
                                if (_includeSecurity)
                                {
                                    File.SetAccessControl(xamlFile, security);
                                }
                            }
                        }
                        if (options.SaveZaml)
                        {
                            string zamlFile = _fileReader.ZamlFile;
                            if (!string.IsNullOrWhiteSpace(zamlFile) &&
                                File.Exists(zamlFile))
                            {
                                File.SetAttributes(zamlFile, fileAttr);

                                // if required to set the security or access control
                                if (_includeSecurity)
                                {
                                    File.SetAccessControl(zamlFile, security);
                                }
                            }
                        }

                        if (drawing != null && options.GenerateImage)
                        {
                            _fileReader.SaveImage(svgFileName, target,
                                                  options.EncoderType);
                            string imageFile = _fileReader.ImageFile;
                            if (!string.IsNullOrWhiteSpace(imageFile) &&
                                File.Exists(imageFile))
                            {
                                File.SetAttributes(imageFile, fileAttr);

                                // if required to set the security or access control
                                if (_includeSecurity)
                                {
                                    File.SetAccessControl(imageFile, security);
                                }
                            }
                        }

                        if (drawing != null)
                        {
                            _convertedCount++;
                        }

                        if (_fileReader.WriterErrorOccurred)
                        {
                            _writerErrorOccurred = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        _errorFiles.Add(svgFileName);

                        if (_continueOnError)
                        {
                            StringBuilder builder = new StringBuilder();
                            builder.AppendLine("Error converting: " + svgFileName);
                            builder.AppendFormat("Error: Exception ({0})", ex.GetType());
                            builder.AppendLine();
                            builder.AppendLine(ex.Message);
                            builder.AppendLine(ex.ToString());

                            _worker.ReportProgress(0, builder.ToString());
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
        }
示例#14
0
		public static DrawingGroup ReadDrawing(string svgFileName)
		{
			var settings = new WpfDrawingSettings()
			{
				IncludeRuntime = false,
				TextAsGeometry = true,
				OptimizePath = true,
			};
			using (FileSvgReader reader = new FileSvgReader(settings))
				return reader.Read(svgFileName);
		}
示例#15
0
 public void Handwheel1() //pure svg# without any modifications
 {
     var fileReader = new FileSvgReader(null);
     DrawingGroup drawing = fileReader.Read("TestFiles\\Handwheel.svg");
     XmlXamlWriter writer = new XmlXamlWriter(null);
     var xaml = writer.Save(drawing);
     Console.WriteLine(xaml);
     Clipboard.SetText(xaml);
 }
示例#16
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);
        }
示例#17
0
        /// <summary>
        /// Performs the conversion of a valid SVG source file to the
        /// <see cref="DrawingGroup"/>.
        /// </summary>
        /// <returns>
        /// This returns <see cref="DrawingGroup"/> if successful; otherwise, it
        /// returns <see langword="null"/>.
        /// </returns>
        protected virtual DrawingGroup CreateDrawing()
        {
            Uri svgSource = this.GetAbsoluteUri();

            DrawingGroup drawing = null;

            if (svgSource == null)
            {
                return(drawing);
            }

            try
            {
                string scheme = svgSource.Scheme;
                if (String.IsNullOrEmpty(scheme))
                {
                    return(null);
                }

                WpfDrawingSettings settings = new WpfDrawingSettings();
                settings.IncludeRuntime = _includeRuntime;
                settings.TextAsGeometry = _textAsGeometry;
                settings.OptimizePath   = _optimizePath;
                if (_culture != null)
                {
                    settings.CultureInfo = _culture;
                }

                switch (scheme)
                {
                case "file":
                //case "ftp":
                //case "https":
                case "http":
                    using (FileSvgReader reader =
                               new FileSvgReader(settings))
                    {
                        drawing = reader.Read(svgSource);
                    }
                    break;

                case "pack":
                    StreamResourceInfo svgStreamInfo = null;
                    if (svgSource.ToString().IndexOf("siteoforigin",
                                                     StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        svgStreamInfo = Application.GetRemoteStream(svgSource);
                    }
                    else
                    {
                        svgStreamInfo = Application.GetResourceStream(svgSource);
                    }

                    Stream svgStream = (svgStreamInfo != null) ?
                                       svgStreamInfo.Stream : null;

                    if (svgStream != null)
                    {
                        string fileExt      = Path.GetExtension(svgSource.ToString());
                        bool   isCompressed = !String.IsNullOrEmpty(fileExt) &&
                                              String.Equals(fileExt, ".svgz",
                                                            StringComparison.OrdinalIgnoreCase);

                        if (isCompressed)
                        {
                            using (svgStream)
                            {
                                using (GZipStream zipStream =
                                           new GZipStream(svgStream, CompressionMode.Decompress))
                                {
                                    using (FileSvgReader reader =
                                               new FileSvgReader(settings))
                                    {
                                        drawing = reader.Read(zipStream);
                                    }
                                }
                            }
                        }
                        else
                        {
                            using (svgStream)
                            {
                                using (FileSvgReader reader =
                                           new FileSvgReader(settings))
                                {
                                    drawing = reader.Read(svgStream);
                                }
                            }
                        }
                    }
                    break;
                }
            }
            catch
            {
                if (DesignerProperties.GetIsInDesignMode(new DependencyObject()) ||
                    LicenseManager.UsageMode == LicenseUsageMode.Designtime)
                {
                    return(drawing);
                }

                throw;
            }

            return(drawing);
        }
示例#18
0
 /// <summary>
 /// 创建SvgDrawingCanvas(Svg画布)
 /// </summary>
 /// <param name="svgFileName">svg文件路径</param>
 /// <returns>SvgDrawingCanvas(Svg画布)</returns>
 public static SvgDrawingCanvas CreateSvgDrawingCanvas(string svgFileName)
 {
     FileSvgReader svgReader = new FileSvgReader(null);
     svgReader.Read(svgFileName);
     return CreateSvgDrawingCanvas(svgReader);
 }
示例#19
0
        /// <summary>
        /// Performs the conversion of a valid SVG source file to the 
        /// <see cref="DrawingImage"/> that is set as the value of the target 
        /// property for this markup extension.
        /// </summary>
        /// <param name="serviceProvider">
        /// Object that can provide services for the markup extension.
        /// </param>
        /// <returns>
        /// This returns <see cref="DrawingImage"/> if successful; otherwise, it
        /// returns <see langword="null"/>.
        /// </returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            Uri svgSource = this.GetUri(serviceProvider);

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

            try
            {
                string scheme = svgSource.Scheme;
                if (String.IsNullOrEmpty(scheme))
                {
                    return null;
                }

                WpfDrawingSettings settings = new WpfDrawingSettings();
                settings.IncludeRuntime = _includeRuntime;
                settings.TextAsGeometry = _textAsGeometry;
                settings.OptimizePath   = _optimizePath;
                if (_culture != null)
                {
                    settings.CultureInfo = _culture;
                }

                switch (scheme)
                {
                    case "file":
                    //case "ftp":
                    //case "https":
                    case "http":
                        using (FileSvgReader reader =
                            new FileSvgReader(settings))
                        {
                            DrawingGroup drawGroup = reader.Read(svgSource);

                            if (drawGroup != null)
                            {
                                return new DrawingImage(drawGroup);
                            }
                        }
                        break;
                    case "pack":
                        StreamResourceInfo svgStreamInfo = null;
                        if (svgSource.ToString().IndexOf("siteoforigin",
                            StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            svgStreamInfo = Application.GetRemoteStream(svgSource);
                        }
                        else
                        {
                            svgStreamInfo = Application.GetResourceStream(svgSource);
                        }

                        Stream svgStream = (svgStreamInfo != null) ?
                            svgStreamInfo.Stream : null;

                        if (svgStream != null)
                        {
                            string fileExt = Path.GetExtension(svgSource.ToString());
                            bool isCompressed = !String.IsNullOrEmpty(fileExt) &&
                                String.Equals(fileExt, ".svgz",
                                StringComparison.OrdinalIgnoreCase);

                            if (isCompressed)
                            {
                                using (svgStream)
                                {
                                    using (GZipStream zipStream =
                                        new GZipStream(svgStream, CompressionMode.Decompress))
                                    {
                                        using (FileSvgReader reader =
                                            new FileSvgReader(settings))
                                        {
                                            DrawingGroup drawGroup = reader.Read(
                                                zipStream);

                                            if (drawGroup != null)
                                            {
                                                return new DrawingImage(drawGroup);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                using (svgStreamInfo.Stream)
                                {
                                    using (FileSvgReader reader =
                                        new FileSvgReader(settings))
                                    {
                                        DrawingGroup drawGroup = reader.Read(
                                            svgStreamInfo.Stream);

                                        if (drawGroup != null)
                                        {
                                            return new DrawingImage(drawGroup);
                                        }
                                    }
                                }
                            }
                        }
                        break;
                }

            }
            catch
            {
                if (DesignerProperties.GetIsInDesignMode(new DependencyObject()) ||
                    LicenseManager.UsageMode == LicenseUsageMode.Designtime)
                {
                    return null;
                }

                throw;
            }

            return null;
        }
示例#20
0
 /// <summary>
 /// 创建SvgDrawingCanvas(Svg画布)
 /// </summary>
 /// <param name="svgTextReader">svg文件的XmlReader</param>
 /// <returns>SvgDrawingCanvas(Svg画布)</returns>
 public static SvgDrawingCanvas CreateSvgDrawingCanvas(XmlReader svgXmlReader)
 {
     FileSvgReader svgReader = new FileSvgReader(null);
     svgReader.Read(svgXmlReader);
     return CreateSvgDrawingCanvas(svgReader);
 }
示例#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);
        }
示例#22
0
        /// <summary>
        /// 创建SVG图像
        /// </summary>
        /// <param name="svgStream">SVG文件流</param>
        /// <returns>SVG图像</returns>
        public static SvgImage CreateSvgImage(Stream svgStream)
        {
            var svgImage = new SvgImage();
            var drawingImage = (DrawingImage)null;
            var svgReader = new FileSvgReader(null);

            svgReader.Read(svgStream);
            drawingImage = new DrawingImage(svgReader.Drawing);
            svgImage.Source=drawingImage;
            svgImage.Stretch = Stretch.Fill;

            return svgImage;
        }
示例#23
0
        internal static DrawingGroup SvgFileToWpfObject(string filepath, WpfDrawingSettings wpfDrawingSettings)
        {
            if (wpfDrawingSettings == null) //use defaults if null
                wpfDrawingSettings = new WpfDrawingSettings { IncludeRuntime = false, TextAsGeometry = false, OptimizePath = true };
            var reader = new FileSvgReader(wpfDrawingSettings);

            //this is straight forward, but in this version of the dlls there is an error when name starts with a digit
            //var uri = new Uri(Path.GetFullPath(filepath));
            //reader.Read(uri); //accessing using the filename results is problems with the uri (if the dlls are packed in ressources)
            //return reader.Drawing;

            //this should be faster, but using CreateReader will loose text items like "JOG" ?!
            //using (var stream = File.OpenRead(Path.GetFullPath(filepath)))
            //{
            //    //workaround: error when Id starts with a number
            //    var doc = XDocument.Load(stream);
            //    ReplaceIdsWithNumbers(doc.Root); //id="3d-view-icon" -> id="_3d-view-icon"
            //    using (var xmlReader = doc.CreateReader())
            //    {
            //        reader.Read(xmlReader);
            //        return reader.Drawing;
            //    }
            //}

            //workaround: error when Id starts with a number
            var doc = XDocument.Load(Path.GetFullPath(filepath));
            ReplaceIdsWithNumbers(doc.Root); //id="3d-view-icon" -> id="_3d-view-icon"
            using (var ms = new MemoryStream())
            {
                doc.Save(ms);
                ms.Position = 0;
                reader.Read(ms);
                return reader.Drawing;
            }
        }
示例#24
0
 public void Handwheel1()
 {
     var fileReader = new FileSvgReader(null);
     DrawingGroup drawing = fileReader.Read("..\\..\\TestFiles\\Handwheel.svg");
     XmlXamlWriter writer = new XmlXamlWriter(null);
     var xaml = writer.Save(drawing);
     Console.WriteLine(xaml);
     Clipboard.SetText(xaml);
 }