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))); } }
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(); } } } }
public DrawingPage() { InitializeComponent(); _wpfSettings = new WpfDrawingSettings(); _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = false; _fileReader.SaveZaml = false; this.Loaded += new RoutedEventHandler(OnPageLoaded); }
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))); }
public MainWindow() { InitializeComponent(); _titleBase = this.Title; this.Loaded += new RoutedEventHandler(OnWindowLoaded); //this.Unloaded += new RoutedEventHandler(OnWindowUnloaded); this.Closing += new CancelEventHandler(OnWindowClosing); _fileReader = new FileSvgReader(); _fileReader.SaveXaml = false; _fileReader.SaveZaml = false; }
/// <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); }
public ConsoleFileConverter(string sourceFile) { _sourceFile = sourceFile; _wpfSettings = new WpfDrawingSettings(); _wpfSettings.CultureInfo = _wpfSettings.NeutralCultureInfo; _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = false; _fileReader.SaveZaml = false; _worker = new ConsoleWorker(); //_worker.WorkerReportsProgress = true; //_worker.WorkerSupportsCancellation = true; _worker.DoWork += new DoWorkEventHandler(OnWorkerDoWork); _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnWorkerCompleted); _worker.ProgressChanged += new ProgressChangedEventHandler(OnWorkerProgressChanged); }
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 FileListConverterOutput() { InitializeComponent(); _wpfSettings = new WpfDrawingSettings(); _wpfSettings.CultureInfo = _wpfSettings.NeutralCultureInfo; _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = false; _fileReader.SaveZaml = false; _worker = new BackgroundWorker(); _worker.WorkerReportsProgress = true; _worker.WorkerSupportsCancellation = true; _worker.DoWork += new DoWorkEventHandler(OnWorkerDoWork); _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnWorkerCompleted); _worker.ProgressChanged += new ProgressChangedEventHandler(OnWorkerProgressChanged); _continueOnError = true; }
public DrawingPage() { InitializeComponent(); _saveXaml = true; _wpfSettings = new WpfDrawingSettings(); _wpfSettings.CultureInfo = _wpfSettings.NeutralCultureInfo; _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = _saveXaml; _fileReader.SaveZaml = false; mouseHandlingMode = MouseHandlingMode.None; string workDir = Path.Combine(Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location), "XamlDrawings"); _workingDir = new DirectoryInfo(workDir); this.Loaded += new RoutedEventHandler(OnPageLoaded); }
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); }
public FileConverterOutput() { InitializeComponent(); textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("XML"); TextEditorOptions options = textEditor.Options; if (options != null) { options.AllowScrollBelowDocument = true; options.EnableHyperlinks = true; options.EnableEmailHyperlinks = true; //options.ShowSpaces = true; //options.ShowTabs = true; //options.ShowEndOfLine = true; } textEditor.IsReadOnly = true; textEditor.ShowLineNumbers = true; _foldingManager = FoldingManager.Install(textEditor.TextArea); _foldingStrategy = new XmlFoldingStrategy(); _wpfSettings = new WpfDrawingSettings(); _wpfSettings.CultureInfo = _wpfSettings.NeutralCultureInfo; _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = false; _fileReader.SaveZaml = false; mouseHandlingMode = MouseHandlingMode.None; _worker = new BackgroundWorker(); _worker.WorkerReportsProgress = true; _worker.WorkerSupportsCancellation = true; _worker.DoWork += new DoWorkEventHandler(OnWorkerDoWork); _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnWorkerCompleted); _worker.ProgressChanged += new ProgressChangedEventHandler(OnWorkerProgressChanged); }
public DirectoryConverterOutput() { InitializeComponent(); _wpfSettings = new WpfDrawingSettings(); _wpfSettings.CultureInfo = _wpfSettings.NeutralCultureInfo; _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = false; _fileReader.SaveZaml = false; _worker = new BackgroundWorker(); _worker.WorkerReportsProgress = true; _worker.WorkerSupportsCancellation = true; _worker.DoWork += OnWorkerDoWork; _worker.RunWorkerCompleted += OnWorkerCompleted; _worker.ProgressChanged += OnWorkerProgressChanged; _isOverwrite = true; _isRecursive = true; _continueOnError = true; }
public ConsoleDirectoryConverter(string sourceDir) { _sourceDir = sourceDir; _wpfSettings = new WpfDrawingSettings(); _wpfSettings.CultureInfo = _wpfSettings.NeutralCultureInfo; _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = false; _fileReader.SaveZaml = false; _worker = new ConsoleWorker(); //_worker.WorkerReportsProgress = true; //_worker.WorkerSupportsCancellation = true; _worker.DoWork += new DoWorkEventHandler(OnWorkerDoWork); _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnWorkerCompleted); _worker.ProgressChanged += new ProgressChangedEventHandler(OnWorkerProgressChanged); _isOverwrite = true; _isRecursive = true; _continueOnError = true; }
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 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); }
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); }
/// <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); }); } } } } }
/// <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); }
/// <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); }
/// <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; }
/// <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); }
/// <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); }
/// <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; }
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); }
/// <summary> /// 创建SvgDrawingCanvas(Svg画布) /// </summary> /// <param name="svgReader"></param> /// <returns>SvgDrawingCanvas(Svg画布)</returns> private static SvgDrawingCanvas CreateSvgDrawingCanvas(FileSvgReader svgReader) { SvgDrawingCanvas svgCanvas = new SvgDrawingCanvas(); svgCanvas.RenderDiagrams(svgReader.Drawing); return svgCanvas; }
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; } }
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); }