public static BitmapInfo LoadBitmap(object bitmapStream) { if (bitmapStream is Stream stream) { byte[] buffer = new byte[4]; stream.Position = 0; stream.Read(buffer, 0, 4); stream.Position = 0; if (System.Text.Encoding.UTF8.GetString(buffer, 0, 4).ToLower().Equals("<svg")) { var svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); return(new BitmapInfo { Svg = svg }); } var image = SKImage.FromEncodedData(SKData.CreateCopy(stream.ToBytes())); return(new BitmapInfo { Bitmap = image }); } if (bitmapStream is Sprite sprite) { return(new BitmapInfo { Sprite = sprite }); } return(null); }
public SvgButton(string DefaultFile, string TouchedFile, SKMatrix Scale, Context context) { var assets = context.Assets; SvgTouched = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assets.Open(TouchedFile))) { SvgTouched.Load(stream.BaseStream); } // SvgTouched.Load(TouchedFile); SvgDefault = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assets.Open(DefaultFile))) { SvgDefault.Load(stream.BaseStream); } // SvgDefault.Load(DefaultFile); scale = Scale; /* #TODO * if (UIScreen.MainScreen.Scale > 2) * { * scale = SKMatrix.MakeScale(Scale.ScaleX * 1.5f, Scale.ScaleY * 1.5f); * } * else * { * scale = Scale; * } */ }
/// <summary> /// Creates the image. /// </summary> /// <returns>The image.</returns> /// <param name="stream">Stream.</param> /// <param name="width">Width.</param> /// <param name="height">Height.</param> /// <param name="color">Color.</param> public static Task <Stream> CreateImage(Stream stream, double width, double height, Color color) { var screenScale = SvgImageSource.ScreenScale; var svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); var size = CalcSize(svg.Picture.CullRect.Size, width, height); var scale = CalcScale(svg.Picture.CullRect.Size, size, screenScale); var matrix = SKMatrix.MakeScale(scale.Item1, scale.Item2); using (var bitmap = new SKBitmap((int)(size.Width * screenScale), (int)(size.Height * screenScale))) using (var canvas = new SKCanvas(bitmap)) using (var paint = new SKPaint()) { if (!color.IsDefault) { paint.ColorFilter = SKColorFilter.CreateBlendMode(ToSKColor(color), SKBlendMode.SrcIn); } canvas.Clear(SKColors.Transparent); // very very important! canvas.DrawPicture(svg.Picture, ref matrix, paint); using (var image = SKImage.FromBitmap(bitmap)) using (var encoded = image.Encode()) { var imageStream = new MemoryStream(); encoded.SaveTo(imageStream); imageStream.Position = 0; return(Task.FromResult(imageStream as Stream)); } } }
/// <summary> /// Load SVG image from resources /// </summary> public static SkiaSharp.Extended.Svg.SKSvg GetSvgImage(string assemblyName, string resourceKey) { SkiaSharp.Extended.Svg.SKSvg svg = null; string resourceId = assemblyName + "." + resourceKey; if (!SvgImage.SvgCache.TryGetValue(resourceId, out svg)) { Assembly assembly = Assembly.Load(new AssemblyName(assemblyName)); using (Stream stream = assembly.GetManifestResourceStream(resourceId)) { if (stream == null) { throw new FileNotFoundException($"SvgIcon : could not load SVG file {resourceId} in assembly {assembly}. Make sure the ID is correct, the file is there and it is set to Embedded Resource build action."); } svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); SvgImage.SvgCache.Add(resourceId, svg); } } return(svg); }
public SvgButton(string DefaultFile, string TouchedFile, SKMatrix Scale) { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(UIPhotoTakerView)).Assembly; SvgTouched = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assembly.GetManifestResourceStream(RESOURCE_PREFIX + TouchedFile))) { SvgTouched.Load(stream.BaseStream); } SvgDefault = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assembly.GetManifestResourceStream(RESOURCE_PREFIX + DefaultFile))) { SvgDefault.Load(stream.BaseStream); } if (UIScreen.MainScreen.Scale > 2) { scale = SKMatrix.MakeScale(Scale.ScaleX * 1.5f, Scale.ScaleY * 1.5f); } else { scale = Scale; } }
public static SkiaSharp.Extended.Svg.SKSvg GetCache(string imageName) { if (string.IsNullOrEmpty(imageName)) { return(null); } if (!SvgImage.SvgCache.TryGetValue(imageName, out var svg)) { var assemply = typeof(SKScrollView).Assembly; var keyName = $"{assemply.GetName().Name}.Assets.{imageName}.svg"; using (var stream = assemply.GetManifestResourceStream(keyName)) { if (stream != null) { svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); SvgImage.SvgCache[imageName] = svg; } else { SvgImage.SvgCache[imageName] = null; } } } return(svg); }
private void Svg2Png(PlotModel model) { SvgExporter exporter = new SvgExporter { Width = 600, Height = 400 }; var svg = new SkiaSharp.Extended.Svg.SKSvg(); var imgQuality = 80; using (FileStream fs = System.IO.File.Create("temp.svg")) { exporter.Export(model, fs); } using (FileStream png = System.IO.File.Create("img.png")) { var pict = svg.Load("temp.svg"); var dimen = new SKSizeI( (int)Math.Ceiling(pict.CullRect.Width), (int)Math.Ceiling(pict.CullRect.Height) ); var matrix = SKMatrix.MakeScale(1, 1); var img = SKImage.FromPicture(pict, dimen, matrix); // convert to PNG var skdata = img.Encode(SKEncodedImageFormat.Png, imgQuality); skdata.SaveTo(png); } }
static public F9PImageData Create(System.IO.Stream stream, string key) { // necessary if we can't random access the stream - which should be the case with url streams using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); //TODO: Try opening SVG with SKBitmap.Decode. Could be viable alternative to the following? using (var sr = new StreamReader(memoryStream)) { if (IsSvg(sr)) { var skSvg = new SkiaSharp.Extended.Svg.SKSvg(); skSvg.Load(memoryStream); return(new F9PImageData(skSvg, key)); } var skBitmap = SKBitmap.Decode(memoryStream); if (skBitmap != null) { return(new F9PImageData(skBitmap, key)); } } } return(null); }
public ImageSource ProvideValue(IServiceProvider serviceProvider) { if (string.IsNullOrEmpty(ResourceName)) { return(null); } if (!imagedataDictionary.TryGetValue(ResourceName, out var imagedata)) { var assembly = GetType().GetTypeInfo().Assembly; var assemblyName = assembly.GetName().Name; var skSvg = new SkiaSharp.Extended.Svg.SKSvg(new SKSize(Width, Height)); skSvg.Load(assembly.GetManifestResourceStream(assemblyName + "." + ResourceName)); var bitmap = new SKBitmap(Width, Height); var canvas = new SKCanvas(bitmap); canvas.Clear(SKColors.Transparent); canvas.DrawPicture(skSvg.Picture); canvas.Flush(); canvas.Save(); imagedata = SKImage.FromBitmap(bitmap).ToRasterImage().Encode(SKEncodedImageFormat.Png, 100); imagedataDictionary.Add(ResourceName, imagedata); } return(ImageSource.FromStream(() => imagedata.AsStream())); }
protected override Task OnInit() { svg = new SKSvg(); using (var stream = SampleMedia.Images.OpacitySvg) svg.Load(stream); return(base.OnInit()); }
private SkiaSharp.Extended.Svg.SKSvg CreateSKSvg() { var stream = GetEmbeddedResourceStream(); var svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); return(svg); }
/// <summary> /// Назначить из Assets\svg SVG-картинку на ImageView /// </summary> /// <param name="imgView"></param> /// <param name="fileName"></param> /// <param name="wantedWidth"></param> /// <param name="wantedHeight"></param> /// <param name="preprocess"></param> public static void AssignSvg([NotNull] ImageView imgView, string fileName, Action <XmlDocument> preprocess, int?wantedWidth = null, int?wantedHeight = null) { if (wantedWidth == null) { wantedWidth = imgView.Width; } if (wantedHeight == null) { wantedHeight = imgView.Height; } const int bestQuality = 100; var parentColor = TryGetBackgroundColor(imgView); var viewActivity = (Activity)imgView.Context; using (var reader = new StreamReader(viewActivity.Assets.Open(Path.Combine("svg", Path.ChangeExtension(fileName, "svg").AssertNull())))) { var xmlDoc = new XmlDocument(); xmlDoc.Load(reader); xmlDoc.DocumentElement.VoidAssertNull(); xmlDoc.DocumentElement.SetAttribute("width", wantedWidth.ToString()); xmlDoc.DocumentElement.SetAttribute("height", wantedHeight.ToString()); preprocess?.Invoke(xmlDoc); if (parentColor.HasValue) { var bkColorRect = xmlDoc.CreateElement("rect"); bkColorRect.SetAttribute("style", $"fill: {parentColor.Value.ToHtmlValue()}"); bkColorRect.SetAttribute("x", "0"); bkColorRect.SetAttribute("y", "0"); bkColorRect.SetAttribute("width", wantedWidth.ToString()); bkColorRect.SetAttribute("height", wantedHeight.ToString()); xmlDoc.DocumentElement.AssertNull().InsertAfter(bkColorRect, null); } using (var alterStream = new MemoryStream()) { xmlDoc.Save(alterStream); alterStream.Seek(0, SeekOrigin.Begin); var svg = new SkiaSharp.Extended.Svg.SKSvg(new SKSize(wantedWidth.Value, wantedHeight.Value)); svg.Load(alterStream); using (var svgBitmap = new SKBitmap((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height)) { using (var canvas = new SKCanvas(svgBitmap)) { canvas.DrawPicture(svg.Picture); canvas.Flush(); canvas.Save(); } using (var image = SKImage.FromBitmap(svgBitmap)) using (var data = image.Encode(SKEncodedImageFormat.Png, bestQuality)) { var bmpArray = data.ToArray(); imgView.SetImageBitmap(BitmapFactory.DecodeByteArray(bmpArray, 0, bmpArray.Length)); } } } } }
private void OnSourceChanged(Uri oldValue, Uri newValue) { var fixedUri = new Uri(newValue.OriginalString.Replace("ms-resource:///Files", "ms-appx:///")); loader?.Dispose(); loader = Observable .FromAsync(() => GetStream(fixedUri)) .Subscribe(stream => svg.Load(stream)); }
private void LoadSvg(string svgName) { // create a new SVG object svg = new SkiaSharp.Extended.Svg.SKSvg(); // load the SVG document from a stream using (var stream = GetImageStream(svgName)) svg.Load(stream); }
void OnPaintSurface(object sender, SKPaintSurfaceEventArgs e) { if (string.IsNullOrEmpty(Source)) { return; } if (Clicked == null && !AddPadding) { _padding = 0; } try { if (_fileContent == null) { _fileContent = Source.GetFileContents(); } if (Clicked == null) { _padding = 0; } var svg = new SkiaSharp.Extended.Svg.SKSvg(); var bytes = System.Text.Encoding.UTF8.GetBytes(_fileContent); var stream = new MemoryStream(bytes); svg.Load(stream); var canvas = e.Surface.Canvas; using (var paint = new SKPaint()) { if (Color != Color.Lime) { //Set the paint color paint.ColorFilter = SKColorFilter.CreateBlendMode(Color.ToSKColor(), SKBlendMode.SrcIn); } int multiplier = (int)(e.Info.Width / WidthRequest); //Scale up the SVG image to fill the canvas float canvasMin = Math.Min(e.Info.Width - _padding * 2 * multiplier, e.Info.Height - _padding * 2 * multiplier); float svgMax = Math.Max(svg.Picture.CullRect.Width, svg.Picture.CullRect.Height); float scale = canvasMin / svgMax; var matrix = SKMatrix.MakeScale(scale, scale); matrix.TransX = _padding * multiplier; matrix.TransY = _padding * multiplier; canvas.Clear(Color.Transparent.ToSKColor()); canvas.DrawPicture(svg.Picture, ref matrix, paint); } } catch (Exception ex) { Log.Instance.WriteLine($"Error drawing SvgImage w/ ImagePath {Source}: {ex}"); } }
public static ImageSource GetAsImageSource(string svgImage, float width, float height, Color color) { var scaleFactor = 0; #if __IOS__ scaleFactor = (int)UIKit.UIScreen.MainScreen.Scale; #elif __ANDROID__ // В MainActivity добавлено статическое свойство Current. scaleFactor = MainActivity.Current.Resources.DisplayMetrics.Density #endif var svg = new SkiaSharp.Extended.Svg.SKSvg(); #if __IOS__ svg.Load(svgImage); #elif __ANDROID__ var assetStream = MainActivity.Current.Assets.Open(svgImage); svg.Load(assetStream); #endif var svgSize = svg.Picture.CullRect; var svgMax = Math.Max(svgSize.Width, svgSize.Height); float canvasMin = Math.Min((int)(width * scaleFactor), (int)(height * scaleFactor)); var scale = canvasMin / svgMax; var matrix = SKMatrix.MakeScale(scale, scale); var bitmap = new SKBitmap((int)(width * scaleFactor), (int)(height * scaleFactor)); var paint = new SKPaint() { ColorFilter = SKColorFilter.CreateBlendMode(color.ToSKColor(), SKBlendMode.SrcIn) }; var canvas = new SKCanvas(bitmap); canvas.DrawPicture(svg.Picture, ref matrix, paint); var image = SKImage.FromBitmap(bitmap); var encoded = image.Encode(); var stream = encoded.AsStream(); var source = ImageSource.FromStream(() => stream); return(source); }
private SKPicture LoadScene() { var svg = new SkiaSharp.Extended.Svg.SKSvg(); var fileName = $"SkiaScene.NativeSample.{_fileName}"; var assembly = typeof(SvgSceneRenderer).GetTypeInfo().Assembly; var stream = assembly.GetManifestResourceStream(fileName); var result = svg.Load(stream); return(result); }
private void CanvasViewOnPaintSurface(object sender, SKPaintSurfaceEventArgs args) { _canvas = args.Surface.Canvas; _canvas.Clear(); if (string.IsNullOrEmpty(ResourceId)) { return; } if (ResourceId.Contains("resource://")) { ResourceId = ResourceId.Replace("resource://", ""); } using (Stream stream = GetType().Assembly.GetManifestResourceStream(ResourceId)) { SkiaSharp.Extended.Svg.SKSvg svg = new SkiaSharp.Extended.Svg.SKSvg(); if (ResourceId.Contains("storage")) { svg.Load(ResourceId); } else { svg.Load(stream); } SKImageInfo info = args.Info; _canvas.Translate(info.Width / 2f, info.Height / 2f); SKRect bounds = svg.ViewBox; float xRatio = info.Width / bounds.Width; float yRatio = info.Height / bounds.Height; float ratio = Math.Min(xRatio, yRatio); _canvas.Scale(ratio); _canvas.Translate(-bounds.MidX, -bounds.MidY); _canvas.DrawPicture(svg.Picture); } }
public SvgButton(string DefaultFile, string ToggledFile, string TouchedFile, SKMatrix Scale, Context Context) : this(DefaultFile, TouchedFile, Scale, Context) { var assets = Context.Assets; SvgToggled = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assets.Open(ToggledFile))) { SvgToggled.Load(stream.BaseStream); } }
public SvgButton(string DefaultFile, string ToggledFile, string TouchedFile, SKMatrix Scale) : this(DefaultFile, TouchedFile, Scale) { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(UIPhotoTakerView)).Assembly; SvgToggled = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assembly.GetManifestResourceStream(RESOURCE_PREFIX + ToggledFile))) { SvgToggled.Load(stream.BaseStream); } }
internal static SKPicture SvgToSKPicture(string xml) { if (!string.IsNullOrEmpty(xml)) { using (var stream = new StringReader(xml)) using (var reader = XmlReader.Create(stream)) { var svg = new SkiaSharp.Extended.Svg.SKSvg(); return(svg.Load(reader)); } } return(null); }
private void Load(string[] fileNames, string pathToFull, SegmentType type, SegmentWeight weight) { for (var i = 0; i < fileNames.Length; i++) { var svg = new SKSvg(); svg.Load(_assembly.GetManifestResourceStream(fileNames[i])); _svgs[type][weight].Add(i, svg); } var full = new SKSvg(); full.Load(_assembly.GetManifestResourceStream(pathToFull)); _svgs[type][weight].Add(FullSegment, full); Loaded[type][weight].OnNext(Unit.Default); Loaded[type][weight] = new BehaviorSubject <Unit>(Unit.Default); }
public static void LoadAsXMLdocument <T>(this SKSvg svg, string svgNamePath, Action <XmlDocument> actionXmlDoc = null) { var assembly = typeof(T).Assembly; using (var stream = assembly.GetManifestResourceStream(svgNamePath)) { var document = new XmlDocument(); using (var reader = XmlReader.Create(stream)) { document.Load(reader); } actionXmlDoc?.Invoke(document); svg.Load(document.XmlDocumentToStream()); } }
} // SVGPlan constructor /// <summary> /// This function reads the plan from an SVG file. It is a helper function for the Plan constructor. /// </summary> /// <param name="filePath">Full path incl. filename</param> /// <returns></returns> private SKPicture loadPlan(string filePath) { SKPicture LoadedPlan = null; try { LoadedPlan = SVGCanvas.Load(filePath); } catch (Exception ex) { string errorString = "Error loading SVG plan! "; LogFile.WriteError(errorString + ex.Message); throw new Exception(errorString, ex); } return(LoadedPlan); } // loadPlan()
public static async Task GeneratePng(int width, int height, string filepath, string filename, int quality) { var svg2 = new SKSvg(new SKSize(width, height)); svg2.Load(filepath); using (var image = SKImage.FromPicture(svg2.Picture, new SKSizeI(width, height))) { using (var data = image.Encode(SKEncodedImageFormat.Png, quality)) { // save the data to a stream using (var stream = File.OpenWrite(filename)) { data.SaveTo(stream); await stream.FlushAsync(); } } } }
private void SKCanvasView_PaintSurface(object sender, SKPaintSurfaceEventArgs e) { if (!(sender is SKCanvasView container)) { return; } SKCanvas canvas = e.Surface.Canvas; canvas.Clear(); var scale = (float)(e.Info.Width / container.Width); #if DEBUG #if !WINDOWS_UWP Console.WriteLine("Scale = {0}", scale); #else System.Diagnostics.Debug.WriteLine("Scale = {0}", scale); #endif #endif canvas.Scale(scale); var centerX = (float)container.Width / 2; var centerY = (float)container.Height / 2; canvas.Translate(centerX, centerY); using (var stream = GetType().Assembly.GetManifestResourceStream(@"XamarinFormsSVGdemo.black_cat.svg")) using (var paint = new SKPaint()) { var svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); SKRect bounds = svg.ViewBox; canvas.Save(); canvas.Translate(-bounds.MidX, -bounds.MidY); canvas.DrawPicture(svg.Picture, paint); canvas.Restore(); } }
public static void RenderSvg(this Image view, string uri) { try { var svg = new SKSvg(); var req = (HttpWebRequest)WebRequest.Create(uri); req.BeginGetResponse((ar) => { var res = (ar.AsyncState as HttpWebRequest)?.EndGetResponse(ar) as HttpWebResponse; using (var stream = res?.GetResponseStream()) { if (stream == null) { return; } var picture = svg.Load(stream); using (var image = SKImage.FromPicture(picture, picture.CullRect.Size.ToSizeI())) using (var data = image.Encode(SKEncodedImageFormat.Jpeg, 80)) { var ms = new MemoryStream(); if (data == null || data.IsEmpty) { return; } data.SaveTo(ms); ms.Seek(0, SeekOrigin.Begin); ms.Position = 0; view.Source = ImageSource.FromStream(() => ms); } } }, req); } catch (Exception ex) { Debug.WriteLine($"Failed to render svg: {ex}"); throw; } }
private SKSvg getPicture(string id) { if (loaded.ContainsKey(id)) { return(loaded[id]); } var svg = new SKSvg(); var filePath = $"images/reliefs/{id.slice(1)}.svg"; App.LoadRes(filePath, d => { svg.Load(d); loaded[id] = svg; Debug.Log($"{id} viewBox:{svg.ViewBox}"); }); return(svg); }
private void CanvasViewOnPaintSurface(object sender, SKPaintSurfaceEventArgs args) { if (string.IsNullOrEmpty(Source)) { return; } using (var reader = GenerateSVG(args.Info.Width, args.Info.Height).CreateReader()) { var svg = new SKSvg(); svg.Load(reader); var surface = args.Surface; var canvas = surface.Canvas; canvas.Clear(SKColors.White); canvas.DrawPicture(svg.Picture); canvas.Dispose(); } }
static void Main(string[] args) { var srcPath = "../Icons"; var dstPath = "../Icons.Png"; if (!Directory.Exists(dstPath)) { Directory.CreateDirectory(dstPath); } foreach (var inputPath in Directory.GetFiles(srcPath, "*.svg")) { Console.WriteLine(inputPath); using var inputStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read); var outputPath = Path.Combine(dstPath, Path.GetFileNameWithoutExtension(inputPath) + ".png"); var quality = 100; var svg = new SkiaSharp.Extended.Svg.SKSvg(); try { var pict = svg.Load(inputStream); var dimen = new SkiaSharp.SKSizeI( (int)Math.Ceiling(pict.CullRect.Width) * 5, (int)Math.Ceiling(pict.CullRect.Height) * 5 ); var matrix = SKMatrix.MakeScale(5, 5); var img = SKImage.FromPicture(pict, dimen, matrix); // convert to PNG var skdata = img.Encode(SkiaSharp.SKEncodedImageFormat.Png, quality); using (var stream = File.OpenWrite(outputPath)) { skdata.SaveTo(stream); } } catch { } } }