コード例 #1
0
        public Task <bool> LoadImageAsync(NativeImage image, ImageSource imageSource, CancellationToken cancelationToken = default(CancellationToken))
        {
            ImageSource newSource = null;

            switch (imageSource)
            {
            case SKImageImageSource imageImageSource:
                newSource = ImageSource.FromStream(() => ToStream(imageImageSource.Image));
                break;

            case SKBitmapImageSource bitmapImageSource:
                newSource = ImageSource.FromStream(() => ToStream(SKImage.FromBitmap(bitmapImageSource.Bitmap)));
                break;

            case SKPixmapImageSource pixmapImageSource:
                newSource = ImageSource.FromStream(() => ToStream(SKImage.FromPixels(pixmapImageSource.Pixmap)));
                break;

            case SKPictureImageSource pictureImageSource:
                newSource = ImageSource.FromStream(() => ToStream(SKImage.FromPicture(pictureImageSource.Picture, pictureImageSource.Dimensions)));
                break;
            }

            return(handler.LoadImageAsync(image, newSource, cancelationToken));
        }
コード例 #2
0
ファイル: GTKExtensions.cs プロジェクト: zbyszekpy/SkiaSharp
        // Pixbuf

        public static Pixbuf ToPixbuf(this SKPicture picture, SKSizeI dimensions)
        {
            using (var image = SKImage.FromPicture(picture, dimensions))
            {
                return(image.ToPixbuf());
            }
        }
コード例 #3
0
        // System.Drawing.Bitmap

        public static System.Drawing.Bitmap ToBitmap(this SKPicture picture, SKSizeI dimensions)
        {
            using (var image = SKImage.FromPicture(picture, dimensions))
            {
                return(image.ToBitmap());
            }
        }
コード例 #4
0
        // WriteableBitmap

        public static WriteableBitmap ToWriteableBitmap(this SKPicture picture, SKSizeI dimensions)
        {
            using (var image = SKImage.FromPicture(picture, dimensions))
            {
                return(image.ToWriteableBitmap());
            }
        }
コード例 #5
0
 public static Bitmap ToBitmap(this SKPicture skiaPicture, SKSizeI dimensions)
 {
     using (var img = SKImage.FromPicture(skiaPicture, dimensions))
     {
         return(img.ToBitmap());
     }
 }
コード例 #6
0
        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);
            }
        }
コード例 #7
0
        public static Task <SKImage?> ToSKImageAsync(this ImageSource imageSource, CancellationToken cancellationToken = default)
        {
            if (imageSource == null)
            {
                throw new ArgumentNullException(nameof(imageSource));
            }

            return(imageSource switch
            {
                // 1. first try SkiaSharp sources
                SKImageImageSource iis => FromSkia(iis.Image),
                SKBitmapImageSource bis => FromSkia(SKImage.FromBitmap(bis.Bitmap)),
                SKPixmapImageSource xis => FromSkia(SKImage.FromPixels(xis.Pixmap)),
                SKPictureImageSource pis => FromSkia(SKImage.FromPicture(pis.Picture, pis.Dimensions)),

                // 2. then try Stream sources
                StreamImageSource stream => FromStream(stream.Stream.Invoke(cancellationToken)),
                UriImageSource uri => FromStream(uri.GetStreamAsync(cancellationToken)),

                // 3. finally, use the handlers
                FileImageSource file => FromHandler(PlatformToSKImageAsync(file, cancellationToken)),
                FontImageSource font => FromHandler(PlatformToSKImageAsync(font, cancellationToken)),

                // 4. all is lost
                _ => throw new ArgumentException("Unable to determine the type of image source.", nameof(imageSource))
            });
コード例 #8
0
        internal static void ExportSkp(IToolContext context, string path, IContainerView containerView)
        {
            var recorder = new SKPictureRecorder();
            var rect     = new SKRect(0f, 0f, (float)containerView.Width, (float)containerView.Height);
            var canvas   = recorder.BeginRecording(rect);

            using (var skiaContainerPresenter = new SkiaExportContainerPresenter(context, containerView))
            {
                skiaContainerPresenter.Draw(canvas, containerView.Width, containerView.Height, 0, 0, 1.0, 1.0);
            }
            var picture    = recorder.EndRecording();
            var dimensions = new SKSizeI((int)containerView.Width, (int)containerView.Height);

            using (var image = SKImage.FromPicture(picture, dimensions))
            {
                var data = image.EncodedData;
                if (data != null)
                {
                    using (var stream = File.OpenWrite(path))
                    {
                        data.SaveTo(stream);
                    }
                }
            }
            picture.Dispose();
        }
コード例 #9
0
        /// <summary>
        /// Create image tile from all sources that are contained in the MGLStyleFile
        /// </summary>
        /// <param name="styleFile">StyleFile to use</param>
        /// <param name="tile">TileInfo of tile to draw</param>
        /// <param name="tileSize">Tile size of the image tile</param>
        /// <returns>Byte array of image data</returns>
        private static byte[] CreateTile(MGLStyleFile styleFile, TileInfo tile, int tileSize)
        {
            var recorder  = new SKPictureRecorder();
            var stopwatch = new System.Diagnostics.Stopwatch();

            recorder.BeginRecording(new SKRect(0, 0, tileSize, tileSize));

            var canvas = recorder.RecordingCanvas;

            canvas.ClipRect(new SKRect(0, 0, tileSize, tileSize));

            if (styleFile.TileSources != null && styleFile.TileSources.Count > 0)
            {
                // We have one or more sources, so draw each source after the other
                foreach (var source in styleFile.TileSources)
                {
                    stopwatch.Start();

                    var vectorDrawable = source.GetDrawable(tile);

                    stopwatch.Stop();
                    stopwatchResults.Add($"Ellapsed time for GetDrawable of ${source.Name}: {stopwatch.ElapsedMilliseconds} ms");
                    stopwatch.Reset();

                    stopwatch.Start();

                    if (vectorDrawable is SKDrawable drawable)
                    {
                        vectorDrawable.Context.Zoom = float.Parse(tile.Index.Level);
                        vectorDrawable.Context.Tags = null;

                        canvas.Save();
                        canvas.Scale(tileSize / drawable.Bounds.Width);
                        canvas.DrawDrawable(drawable, 0, 0);
                        canvas.Restore();
                    }

                    stopwatch.Stop();
                    stopwatchResults.Add($"Ellapsed time for DrawDrawable of ${source.Name}: {stopwatch.ElapsedMilliseconds} ms");
                    stopwatch.Reset();
                }
            }

            stopwatch.Start();

            var byteArray = SKImage.FromPicture(recorder.EndRecording(), new SKSizeI(tileSize, tileSize), new SKPaint()
            {
                IsAntialias = true
            }).Encode().ToArray();

            stopwatch.Stop();
            stopwatchResults.Add($"Ellapsed time for drawing picture: {stopwatch.ElapsedMilliseconds} ms");

            return(byteArray);
        }
コード例 #10
0
        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();
                    }
                }
            }
        }
コード例 #11
0
        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;
            }
        }
コード例 #12
0
            public static SKBitmapImageSource Load(string source, Aspect aspect, double width, double height)
            {
                // No image needed?
                if (string.IsNullOrWhiteSpace(source) || width <= 0 || height <= 0)
                {
                    return(null);
                }

                // Read the image
                string key = GetKey(source);

                SkiaSharp.Extended.Svg.SKSvg svg = LoadSVG(key);
                CalculateBounds(true, svg, aspect, width, height, out SKMatrix drawMatrix, out SKSizeI pixelSize);

                // Check the cache
                if (ImageSourceCache.TryGetValue(key, out Tuple <SKSizeI, SKBitmapImageSource> cacheEntry))
                {
                    if (cacheEntry.Item1.Width >= pixelSize.Width * (1 - CacheTolerance) &&
                        cacheEntry.Item1.Height >= pixelSize.Height * (1 - CacheTolerance))
                    {
                        // Already cached
                        return(cacheEntry.Item2);
                    }
                    else
                    {
                        // Dispose/remove current entry
                        cacheEntry.Item2.Bitmap?.Dispose();
                        ImageSourceCache.Remove(key);
                    }
                }

                // Convert to an SKBitmapImageSource
                using (SKImage image = SKImage.FromPicture(svg.Picture, pixelSize, drawMatrix))
                {
                    SKBitmapImageSource imageSource = new SKBitmapImageSource()
                    {
                        Bitmap = SKBitmap.FromImage(image)
                    };
                    ImageSourceCache.Add(key, Tuple.Create(pixelSize, imageSource));
                    return(imageSource);
                }
            }
コード例 #13
0
        protected virtual async Task GeneratePng(SKSvg svg2, float width, float height, string filename, int quality, bool icon = false)
        {
            if (svg2?.Picture == null)
            {
                return;
            }

            // calculate the scaling need to fit
            var matrix = SKMatrix.CreateScale(width / svg2.Picture.CullRect.Width, height / svg2.Picture.CullRect.Height);

            using var image = icon
                ? ConvertProfile(SKImage.FromPicture(svg2.Picture, new SKSizeI((int)width, (int)height), matrix), width,
                                 height)
                : SKImage.FromPicture(svg2.Picture, new SKSizeI((int)width, (int)height), matrix);
            using var data = image.Encode(SKEncodedImageFormat.Png, quality);
            // save the data to a stream
            await using var stream = File.OpenWrite(filename);
            data.SaveTo(stream);
            await stream.FlushAsync();
        }
コード例 #14
0
 /// <summary>
 /// Grab the source, and return a png stream
 /// </summary>
 /// <param name="target"></param>
 /// <param name="outgoingData"></param>
 public override void GetData(object target, Stream outgoingData)
 {
     if (target is SKBitmap image1)
     {
         var bitmapSource = image1.Encode(SKEncodedImageFormat.Png, 100).AsStream();
         base.GetData(new SerializableBitmapImage(bitmapSource), outgoingData);
     }
     else if (target is SKImage image2)
     {
         var bitmapSource = image2.Encode(SKEncodedImageFormat.Png, 100).AsStream();
         base.GetData(new SerializableBitmapImage(bitmapSource), outgoingData);
     }
     else if (target is SKSurface image3)
     {
         base.GetData(
             new SerializableBitmapImage(image3.Snapshot().Encode(SKEncodedImageFormat.Png, 100).AsStream()),
             outgoingData);
     }
     else if (target is SKDrawable image4)
     {
         base.GetData(
             new SerializableBitmapImage(SKImage.FromPicture(image4.Snapshot(), new SKSizeI(1024, 1024)).Encode(SKEncodedImageFormat.Png, 100).AsStream()),
             outgoingData);
     }
     else if (target is SKCanvas image5)
     {
         base.GetData(
             new SerializableBitmapImage(new byte[0]),
             outgoingData);
     }
     else if (target is SKPicture image6)
     {
         base.GetData(
             new SerializableBitmapImage(SKImage.FromPicture(image6, new SKSizeI(512, 512)).Encode(SKEncodedImageFormat.Png, 100).AsStream()),
             outgoingData);
     }
     else
     {
         base.GetData(target, outgoingData);
     }
 }
コード例 #15
0
        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
                {
                }
            }
        }
コード例 #16
0
        public string ToImage(int width,
                              int height,
                              _Callback <SKImage> raw_image_callback)
        {
            if (raw_image_callback == null)
            {
                return("Image callback was invalid");
            }

            if (m_layerTree == null)
            {
                return("Scene did not contain a layer tree.");
            }

            if (width == 0 || height == 0)
            {
                return("Image dimensions for scene were invalid.");
            }

            // We can't create an image on this task runner because we don't have a
            // graphics context. Even if we did, it would be slow anyway. Also, this
            // thread owns the sole reference to the layer tree. So we flatten the layer
            // tree into a picture and use that as the thread transport mechanism.

            var picture = m_layerTree.Flatten(new SKRect(0, 0, width, height));

            if (picture == null)
            {
                // Already in Dart scope.
                return("Could not flatten scene into a layer tree.");
            }

            var image = SKImage.FromPicture(picture, new SKSizeI(width, height));

            raw_image_callback(image);

            return(string.Empty);
        }
コード例 #17
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var p = (string)parameter;

            if (_cache.TryGetValue(p, out var val))
            {
                return(val);
            }

            var scale = 1.0f;
            var text  = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 24 24\"><path d=\"" + p + "\" fill=\"#ffffff\"/><path d=\"M0 0h24v24H0z\" fill=\"none\"/></svg>";
            var data  = Encoding.UTF8.GetBytes(text);

            using (var str = new MemoryStream(data))
            {
                var svg   = new SkiaSharp.Extended.Svg.SKSvg();
                var pict  = svg.Load(str);
                var dimen = new SKSizeI(
                    (int)(Math.Ceiling(pict.CullRect.Width) * scale),
                    (int)(Math.Ceiling(pict.CullRect.Height) * scale)
                    );

                var matrix = SKMatrix.CreateScale(scale, scale);
                var img    = SKImage.FromPicture(pict, dimen, matrix);

                // convert to PNG
                var skdata = img.Encode(SKEncodedImageFormat.Png, 75);
                var source = new StreamImageSource()
                {
                    Stream = t => Task.FromResult(skdata.AsStream())
                };

                _cache.TryAdd(p, source);

                return(source);
            }
        }
コード例 #18
0
        private static UIImage CreateImageFromWasabeePinSvg(string color, int width, int height)
        {
            if (ImagesCache.ContainsKey(color))
            {
                return(ImagesCache[color]);
            }

            SKPicture picture;
            var       pin = new WasabeePinSvg(color);

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(pin.RawData)))
                picture = new SkiaSharp.Extended.Svg.SKSvg().Load(stream);

            var image        = SKImage.FromPicture(picture, new SKSizeI((int)picture.CullRect.Size.Width, (int)picture.CullRect.Size.Height)).ToUIImage();
            var resizedImage = ResizeImage(image, width, height);

            if (resizedImage is null)
            {
                return(Google.Maps.Marker.MarkerImage(UIColor.Red));
            }

            ImagesCache.Add(color, resizedImage);
            return(resizedImage);
        }
コード例 #19
0
        public static void CreateOgImage(
            [QueueTrigger("ClassifyResultCreate")] string input,
            [Table("ClassifyResult", "ja-en", "{queueTrigger}")] ResponseTableEntity tableEntity,
            [Blob("classifyresultogimage/{queueTrigger}.png", FileAccess.Write)] Stream imageStream,
            ILogger log)
        {
            log.LogInformation($"Handle {input}");
            var response     = JsonConvert.DeserializeObject <Response>(tableEntity.ResponseData);
            var barFactor    = 600;
            var adultBar     = response.Categories.First(x => x.Name == "Adult").Score *barFactor;
            var racyBar      = response.Categories.First(x => x.Name == "Racy").Score *barFactor;
            var offensiveBar = response.Categories.First(x => x.Name == "Offensive").Score *barFactor;
            var svgString    = $@"<?xml version=""1.0""?>
<svg width=""960""
     height=""480""
     xmlns=""http://www.w3.org/2000/svg""
     xmlns:svg=""http://www.w3.org/2000/svg"">
  <g class=""layer"">
    <text fill=""#000000""
          font-family=""Meiryo""
          font-size=""48""
          id=""svg_1""
          stroke=""#000000""
          stroke-width=""0""
          text-anchor=""start""
          x=""32""
          y=""48"">JapaniseTextClassifier</text>
    <switch>
      <foreignObject x=""64""
                     y=""64""
                     width=""832""
                     height=""240"">
        <p xmlns=""http://www.w3.org/1999/xhtml"" style=""font-size: 24px; font-family: Meiryo;"">
          {response.Request.Text}
        </p>
      </foreignObject>

      <text fill=""#000000""
            font-family=""Meiryo""
            font-size=""24""
            id=""svg_2""
            stroke=""#000000""
            stroke-width=""0""
            text-anchor=""start""
            x=""64""
            y=""96"">{response.Request.Text}</text>
    </switch>
    <text fill=""#000000""
          font-family=""Meiryo""
          font-size=""24""
          id=""svg_3""
          stroke=""#000000""
          stroke-width=""0""
          text-anchor=""start""
          x=""64""
          y=""370"">Adult</text>
    <text fill=""#000000""
          font-family=""Meiryo""
          font-size=""24""
          id=""svg_4""
          stroke=""#000000""
          stroke-width=""0""
          text-anchor=""start""
          x=""64""
          y=""410"">Racy</text>
    <text fill=""#000000""
          font-family=""Meiryo""
          font-size=""24""
          id=""svg_5""
          stroke=""#000000""
          stroke-width=""0""
          text-anchor=""start""
          x=""64""
          y=""450"">Offensive</text>
    <rect fill=""#000000""
          height=""32""
          id=""svg_6""
          stroke=""#000000""
          stroke-width=""5""
          width=""{adultBar}""
          x=""240""
          y=""340""/>
    <rect fill=""#000000""
          height=""32""
          id=""svg_7""
          stroke=""#000000""
          stroke-width=""5""
          width=""{racyBar}""
          x=""240""
          y=""380""/>
    <rect fill=""#000000""
          height=""32""
          id=""svg_8""
          stroke=""#000000""
          stroke-width=""5""
          width=""{offensiveBar}""
          x=""240""
          y=""420""/>
  </g>
</svg>";
            var svg          = new SkiaSharp.Extended.Svg.SKSvg();
            var pict         = svg.Load(new MemoryStream(Encoding.UTF8.GetBytes(svgString)));
            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);
            var quality = 90;
            var skdata  = img.Encode(SkiaSharp.SKEncodedImageFormat.Png, quality);

            skdata.SaveTo(imageStream);
            log.LogInformation(svgString);
        }
コード例 #20
0
ファイル: AppleExtensions.cs プロジェクト: zschong/SkiaSharp
        public static CGImage ToCGImage(this SKPicture skiaPicture, SKSizeI dimensions)
        {
            var img = SKImage.FromPicture(skiaPicture, dimensions);

            return(img.ToCGImage());
        }
コード例 #21
0
 public static IHtmlContent Render(this SKPicture picture)
 {
     using var image = SKImage.FromPicture(picture, picture.CullRect.Size.ToSizeI());
     return(Render(image));
 }
コード例 #22
0
        public static Bitmap ToBitmap(this SKPicture skiaPicture, SKSizeI dimensions)
        {
            var img = SKImage.FromPicture(skiaPicture, dimensions);

            return(ToBitmap(img));
        }