public static byte[] CambiarTamanio(string fileContents, int maxWidth, int maxHeight)
        {
            using FileStream ms         = new FileStream(fileContents, FileMode.Open);
            using SKBitmap sourceBitmap = SKBitmap.Decode(ms);

            int height = Math.Min(maxHeight, sourceBitmap.Height);
            int width  = Math.Min(maxWidth, sourceBitmap.Width);

            using SKBitmap scaledBitmap = sourceBitmap.Resize(new SKImageInfo(width, height), SKFilterQuality.High);
            using SKImage scaledImage   = SKImage.FromBitmap(scaledBitmap);
            using SKData data           = scaledImage.Encode();

            return(data.ToArray());
        }
Esempio n. 2
0
        public void ToRasterImageTrueTrueReturnsNonLazy()
        {
            using var data  = SKData.Create(Path.Combine(PathToImages, "baboon.jpg"));
            using var image = SKImage.FromEncodedData(data);

            Assert.True(image.IsLazyGenerated);
            Assert.Null(image.PeekPixels());

            using var nonLazy = image.ToRasterImage(true);
            Assert.NotEqual(image, nonLazy);
            Assert.False(nonLazy.IsLazyGenerated);
            Assert.NotNull(nonLazy.PeekPixels());
            Assert.Equal(nonLazy, nonLazy.ToRasterImage(true));
        }
Esempio n. 3
0
        /// <summary>
        /// Create sprite atlas from a stream
        /// </summary>
        /// <param name="jsonStream">Stream with Json sprite file information</param>
        /// <param name="bitmapAtlasStream">Stream with containing bitmap with sprite atlas bitmap</param>
        public void CreateSprites(Stream jsonStream, Stream bitmapAtlasStream)
        {
            string json;

            using (var reader = new StreamReader(jsonStream))
            {
                json = reader.ReadToEnd();
            }

            var bitmapAtlasData = SKData.Create(bitmapAtlasStream);
            var bitmapAtlas     = SKImage.FromEncodedData(bitmapAtlasData);

            CreateSprites(json, bitmapAtlas);
        }
Esempio n. 4
0
        public static SKImage ToBitmap(int[] ColorIndex, int Width, int Height, SKColor[] Palette)
        {
            int N = Palette.Length;

            byte[]  reds   = new byte[N];
            byte[]  greens = new byte[N];
            byte[]  blues  = new byte[N];
            SKColor cl;
            int     x;

            for (x = 0; x < N; x++)
            {
                cl        = Palette[x];
                reds[x]   = cl.Red;
                greens[x] = cl.Green;
                blues[x]  = cl.Blue;
            }

            int Size  = Width * Height;
            int Size4 = Size * 4;

            byte[] rgb = new byte[Size4];
            int    Index, Index2;
            int    d;

            for (Index = Index2 = 0; Index < Size; Index++)
            {
                d = ColorIndex[Index];

                if (d < 0 || d >= N)
                {
                    rgb[Index2++] = 0;
                    rgb[Index2++] = 0;
                    rgb[Index2++] = 0;
                    rgb[Index2++] = 255;
                }
                else
                {
                    rgb[Index2++] = blues[d];
                    rgb[Index2++] = greens[d];
                    rgb[Index2++] = reds[d];
                    rgb[Index2++] = 255;
                }
            }

            using (SKData Data = SKData.Create(new MemoryStream(rgb)))
            {
                return(SKImage.FromPixelData(new SKImageInfo(Width, Height, SKColorType.Bgra8888), Data, Width * 4));
            }
        }
Esempio n. 5
0
        public static byte[] CreateByteByImgVerifyCode(string verifyCode, int width, int height)
        {
            byte[]   bytes;
            var      text = verifyCode.ToUpper().ToList();
            SKBitmap bmp  = new SKBitmap(width, height);

            using (SKCanvas canvas = new SKCanvas(bmp))
            {
                // 背景色
                canvas.DrawColor(SKColors.White);

                using (SKPaint sKPaint = new SKPaint())
                {
                    sKPaint.TextSize     = 18;                                                                       // 字体大小
                    sKPaint.FakeBoldText = true;
                    sKPaint.IsAntialias  = true;                                                                     // 开启抗锯齿
                    sKPaint.Typeface     = SKTypeface.FromFamilyName("WenQuanYi Micro Hei", SKTypefaceStyle.Normal); //字体

                    SKRect size = new SKRect();
                    sKPaint.MeasureText(text[0].ToString(), ref size); // 计算文字宽度以及高度

                    float _x  = (width - size.Width * text.Count) / 2 - size.Width;
                    float _y  = size.Height;
                    int   num = Next(0, 9);
                    sKPaint.Color = colors[num];
                    // 干扰线
                    for (int i = 0; i < 3; i++)
                    {
                        canvas.DrawLine(Next(0, 40), Next(1, 29), Next(41, 80), Next(1, 29), sKPaint);
                    }
                    // 文字
                    for (int i = 0; i < text.Count; i++)
                    {
                        _x += size.Width + Next(0, 3);
                        _y  = size.Height + Next(5, 15);
                        canvas.DrawText(text[i].ToString(), _x, _y, sKPaint);  // 画文字
                    }
                }
                // 页面展示图片
                using (SKImage img = SKImage.FromBitmap(bmp))
                {
                    using (SKData p = img.Encode())
                    {
                        bytes = p.ToArray();
                    }
                }
            }
            return(bytes);
        }
        public void initialize()
        {
            this.Size          = new Size(500, 500);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.MaximumSize   = new Size(500, 500);
            this.MinimumSize   = new Size(500, 500);

            try
            {
                image_info = new SKImageInfo(width, height);
                surface    = SKSurface.Create(image_info);

                canvas = surface.Canvas;
                canvas.Clear(SKColors.White);

                coordinates_lines_paint             = new SKPaint();
                coordinates_lines_paint.Color       = SKColor.Parse("#d55e00");
                coordinates_lines_paint.IsAntialias = true;
                coordinates_lines_paint.StrokeWidth = 1;
                coordinates_lines_paint.Style       = SKPaintStyle.Stroke;

                graph_paint             = new SKPaint();
                graph_paint.Color       = SKColors.Black;
                graph_paint.IsAntialias = true;
                graph_paint.StrokeWidth = 1;
                graph_paint.Style       = SKPaintStyle.Stroke;

                //points = get_points(-198, height);
                coordinates_lines = new SKPath();
                graph             = new SKPath();
                points            = coordinates();
                graph_coordinates_lines();
                graph_lines(points);

                canvas.DrawPath(coordinates_lines, coordinates_lines_paint);
                canvas.DrawPath(graph, graph_paint);

                image                      = surface.Snapshot();
                data                       = image.Encode(SKEncodedImageFormat.Png, 500);
                memory_stream              = new MemoryStream(data.ToArray());
                bitmap                     = new Bitmap(memory_stream, false);
                this.BackgroundImage       = bitmap;
                this.BackgroundImageLayout = ImageLayout.None;
            }
            catch (System.Exception error)
            {
                Console.WriteLine("" + error);
            }
        }
        public static (byte[] FileContents, int Height, int Width) Resize(byte[] fileContents, int maxWidth, int maxHeight, SKFilterQuality quality = SKFilterQuality.Medium)
        {
            using MemoryStream ms       = new MemoryStream(fileContents);
            using SKBitmap sourceBitmap = SKBitmap.Decode(ms);

            int height = Math.Min(maxHeight, sourceBitmap.Height);
            int width  = Math.Min(maxWidth, sourceBitmap.Width);


            using SKBitmap scaledBitmap = sourceBitmap.Resize(new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Unpremul), quality);

            using SKImage scaledImage = SKImage.FromBitmap(scaledBitmap);
            using SKData data         = scaledImage.Encode();
            return(data.ToArray(), height, width);
        }
Esempio n. 8
0
        private void Save(Canvas3D Canvas, string FileName)
        {
            if (!Directory.Exists("Canvas3D"))
            {
                Directory.CreateDirectory("Canvas3D");
            }

            using (SKImage Image = Canvas.GetBitmap())
            {
                using (SKData Data = Image.Encode(SKEncodedImageFormat.Png, 100))
                {
                    File.WriteAllBytes(Path.Combine("Canvas3D", FileName), Data.ToArray());
                }
            }
        }
Esempio n. 9
0
 public static BitmapDrawable From(SKData data)
 {
     if (data == null)
     {
         throw new ArgumentNullException(nameof(data));
     }
     using (var codec = SKCodec.Create(data))
     {
         if (codec == null)
         {
             return(null);
         }
         return(From(codec));
     }
 }
Esempio n. 10
0
        private void SaveImage(FsPath file, FsPath targetdir, ILog log, SKData data, string?extensionOverride)
        {
            FsPath target = targetdir.Combine(file.Filename);

            if (extensionOverride != null)
            {
                var newname = Path.ChangeExtension(file.Filename, extensionOverride);
                target = targetdir.Combine(newname);
            }
            using (var stream = target.CreateStream(log))
            {
                log.Detail("Saving image: {0}", target);
                data.SaveTo(stream);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Create immutable bitmap from given stream.
        /// </summary>
        /// <param name="stream">Stream containing encoded data.</param>
        public ImmutableBitmap(Stream stream)
        {
            using (var skiaStream = new SKManagedStream(stream))
            {
                _image = SKImage.FromEncodedData(SKData.Create(skiaStream));

                if (_image == null)
                {
                    throw new ArgumentException("Unable to load bitmap from provided data");
                }

                PixelWidth  = _image.Width;
                PixelHeight = _image.Height;
            }
        }
Esempio n. 12
0
        public void LazyRasterCanReadToNonLazy()
        {
            using var data  = SKData.Create(Path.Combine(PathToImages, "baboon.jpg"));
            using var image = SKImage.FromEncodedData(data);
            Assert.True(image.IsLazyGenerated);

            var info = new SKImageInfo(image.Width, image.Height);

            using var copy = SKImage.Create(info);
            using var pix  = copy.PeekPixels();

            Assert.True(image.ReadPixels(pix));
            Assert.False(copy.IsLazyGenerated);
            Assert.NotNull(copy.PeekPixels());
        }
Esempio n. 13
0
        public static SKImage Load(string filePath)
        {
            using var image = Pfim.Pfim.FromFile(filePath);
            var newData = image.Data;
            var stride  = image.Stride;

            var colorType = SkColorType(image, ref newData, ref stride);
            var imageInfo = new SKImageInfo(image.Width, image.Height, colorType);

            using var stream = new SKMemoryStream(newData);
            using var data   = SKData.Create(stream);
            var fromPixelData = SKImage.FromPixelData(imageInfo, data, stride);

            return(fromPixelData);
        }
Esempio n. 14
0
        public static byte[] getCowsayImage(string fcText, bool writeFile = false, bool postTwitter = true)
        {
            SKBitmap fcBitmap;
            SKImage  fcImage;

            using (SKPaint fortunePaint = new SKPaint {
                TextSize = 12.0f, IsAntialias = true, Color = SKColors.Black, IsStroke = false, Typeface = SKTypeface.FromFamilyName("Courier New")
            })
            {
                // analyse the text a little
                int    textWidth = 0, textHeight = 0;
                string longestText = "";
                (textWidth, textHeight, longestText) = calculateTextBounds(fcText);

                // set some bounds
                SKRect bounds = new SKRect();
                fortunePaint.MeasureText(longestText, ref bounds);
                bounds.Bottom = textHeight * fortunePaint.TextSize;
                fcBitmap      = new SKBitmap((int)bounds.Right, (int)bounds.Height);

                using (SKCanvas cowsayCanvas = new SKCanvas(fcBitmap))
                {
                    cowsayCanvas.Clear(SKColors.Transparent);
                    drawTextLines(fcText, 0, 0, fortunePaint, cowsayCanvas);

                    fcImage = SKImage.FromBitmap(fcBitmap);
                    SKData fcPNG = fcImage.Encode(SKEncodedImageFormat.Png, 100);

                    // write image to local file system
                    if (writeFile == true)
                    {
                        using (var filestream = File.OpenWrite("twitter.png"))
                        {
                            fcPNG.SaveTo(filestream);
                        }
                    }

                    // Post Image to Twitter
                    if (postTwitter == true)
                    {
                        FDTwitter tweetThis = new FDTwitter(ConsumerKey, ConsumerKeySecret, AccessToken, AccessTokenSecret);
                        string    response  = tweetThis.PublishToTwitter("Dogsays on " + DateTime.Now.ToShortDateString(), "", fcPNG.ToArray(), true);
                    }

                    return(fcPNG.ToArray());
                }
            }
        }
Esempio n. 15
0
        public static byte[] CreateCaptcha(string code)
        {
            var charList = code.ToList();

            var bmp = new SKBitmap((charList.Count() * 20), 30);

            using (var canvas = new SKCanvas(bmp))
            {
                //背景色

                canvas.DrawColor(SKColors.White);

                using (SKPaint sKPaint = new SKPaint())
                {
                    sKPaint.TextSize    = 16;   //字体大小
                    sKPaint.IsAntialias = true; //开启抗锯齿
                    sKPaint.Typeface    = SKTypeface.FromFamilyName("微软雅黑");
                    var size = new SKRect();
                    sKPaint.MeasureText(charList[0].ToString(), ref size);
                    var temp   = (bmp.Width / 4 - size.Size.Width) / 2;
                    var temp1  = bmp.Height - (bmp.Height - size.Size.Height) / 2;
                    var random = new Random();
                    //画文字
                    for (int i = 0; i < charList.Count; i++)
                    {
                        sKPaint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255),
                                                    (byte)random.Next(0, 255));
                        canvas.DrawText(charList[i].ToString(), temp + 20 * i, temp1, sKPaint);
                    }

                    //画干扰线
                    for (int i = 0; i < 3; i++)
                    {
                        sKPaint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255),
                                                    (byte)random.Next(0, 255));
                        canvas.DrawLine(random.Next(0, 40), random.Next(1, 29), random.Next(41, 80), random.Next(1, 29),
                                        sKPaint);
                    }
                }
            }
            using (SKImage img = SKImage.FromBitmap(bmp))
            {
                using (SKData p = img.Encode())
                {
                    return(p.ToArray());
                }
            }
        }
        /// <summary>
        /// Create a WriteableBitmap from given stream.
        /// </summary>
        /// <param name="stream">Stream containing encoded data.</param>
        public WriteableBitmapImpl(Stream stream)
        {
            using (var skiaStream = new SKManagedStream(stream))
                using (var skData = SKData.Create(skiaStream))
                {
                    _bitmap = SKBitmap.Decode(skData);

                    if (_bitmap == null)
                    {
                        throw new ArgumentException("Unable to load bitmap from provided data");
                    }

                    PixelSize = new PixelSize(_bitmap.Width, _bitmap.Height);
                    Dpi       = SkiaPlatform.DefaultDpi;
                }
        }
Esempio n. 17
0
        /// <summary>
        /// Converts an image to a SkiaSharp SKImage.
        /// </summary>
        /// <param name="image">Image to convert to SKImage type.</param>
        /// <returns>SKImage.</returns>
        internal static SKImage AsSKImage(this ImageBase image)
        {
            var data      = SKData.Create(image.ImageData, image.Size);
            var colorType = image.PixelFormat switch
            {
                // These are unsupported by SkiaSharp: BGRX_32bpp, BGR_24bpp, Gray_16bpp, RGBA_64bpp
                PixelFormat.BGRA_32bpp => SKColorType.Bgra8888,
                PixelFormat.Gray_8bpp => SKColorType.Gray8,
                PixelFormat.Undefined => SKColorType.Unknown,
                PixelFormat.Gray_16bpp => throw new ArgumentException($"Unsupported pixel format: {image.PixelFormat} (e.g. DepthImage)"),
                      _ => throw new ArgumentException($"Unsupported pixel format: {image.PixelFormat}"),
            };
            var info = new SKImageInfo(image.Width, image.Height, colorType);

            return(SKImage.FromPixelData(info, data, image.Stride));
        }
Esempio n. 18
0
        private void InlineImage(FsPath file, RuntimeSettings settings, SKData data, string?extensionOverride)
        {
            string base64 = Convert.ToBase64String(data.ToArray());
            string mime   = Framework.Server.MimeTypes.GetMimeForExtension(file.Extension);
            string fnmame = file.ToString();

            if (extensionOverride != null)
            {
                mime   = Framework.Server.MimeTypes.GetMimeForExtension(extensionOverride);
                fnmame = Path.ChangeExtension(file.ToString(), extensionOverride);
            }

            string key = fnmame.Replace(settings.SourceDirectory.ToString(), settings.OutputDirectory.ToString());

            settings.InlineImgCache.TryAdd(key, $"data:{mime};base64,{base64}");
        }
        /// <summary>
        /// Load the page at the given index in the sorted entry list
        /// </summary>
        /// <param name="index">Index of page to load</param>
        /// <returns>Bitmap of image at index</returns>
        protected override async Task <Bitmap> LoadPage(int index)
        {
            var entry = CurrentEntryList[index];

            using (var entryStream = entry.OpenEntryStream())
            {
                return(await Task.Run(() =>
                {
                    // SkiaSharp is the underlying image library that Avalonia uses, so we use that here
                    var bitmap = new Bitmap(SKData.Create(entryStream).AsStream());
                    return Task.FromResult(bitmap);
                }));
            }

            throw new System.Exception("Error loading page from archive");
        }
Esempio n. 20
0
        public async Task Invoke(HttpContext context)
        {
            PathString path = context.Request.Path;

            // hand to next middleware if we are not dealing with an image
            if (context.Request.Query.Count == 0 || !IsImagePath(path))
            {
                await _next.Invoke(context);

                return;
            }

            // hand to next middleware if we are dealing with an image but it doesn't have any usable resize querystring params
            ResizeParams resizeParams = GetResizeParams(path, context.Request.Query);

            if (!resizeParams.hasParams || (resizeParams.w == 0 && resizeParams.h == 0))
            {
                await _next.Invoke(context);

                return;
            }

            // get the image location on disk
            string imagePath = Path.Combine(
                _env.WebRootPath,
                path.Value.Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar));

            // check file lastwrite
            DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(imagePath);

            if (lastWriteTimeUtc.Year == 1601) // file doesn't exist, pass to next middleware
            {
                await _next.Invoke(context);

                return;
            }

            SKData imageData = GetImageData(imagePath, resizeParams, lastWriteTimeUtc);

            // write to stream
            context.Response.ContentType   = resizeParams.format == "png" ? "image/png" : "image/jpeg";
            context.Response.ContentLength = imageData.Size;
            await context.Response.Body.WriteAsync(imageData.ToArray(), 0, (int)imageData.Size);

            // cleanup
            imageData.Dispose();
        }
        public Stream Assemble()
        {
            // # Set the number of frames per second to display
            // frameRate( frame_rate )

            //SKCanvas canvas = new SKCanvas()
            SKPath  path    = new SKPath();
            Stream  stream  = null;
            SKImage skImage = null;

            try {
                using (var skSurface = SKSurface.Create(new SKImageInfo(w, h))) {
                    var canvas = skSurface.Canvas;
                    // # Sets color space to Hue Saturation Brightness with max values of HSB respectively
                    // colorMode(HSB, 360, 100, 100, 100)

                    //background(0, 0, 100)
                    canvas.Clear(SKColors.White);
                    // rectMode(CORNER)

                    // draw ...
                    draw(canvas);

                    canvas.Flush();

                    //skImage = skSurface.Snapshot();
                    SKPaint paintConvert = SkiaSharpUtility.CreateDefaultPaint();
                    //skImage = SkiaSharpUtility.ScaleSurfaceToImage( skSurface, ImageCanvasSize, size, paintConvert );
                    skImage = skSurface.Snapshot();
                }
                // encode
                SKData skData = SkiaSharpUtility.EncodeImageToSKData(skImage, "png");

                stream = skData.AsStream();
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }
            finally {
                if (skImage != null)
                {
                    skImage.Dispose();
                }
                paint.Dispose();
            }
            return(stream);
        }
Esempio n. 22
0
        public static ImageSource GetResizeImageSourceFromUrl(int size, int quality, string url)
        {
            var httpClient = new System.Net.Http.HttpClient();
            var bytes      = httpClient.GetByteArrayAsync(serverUrl + url).Result;
            var stream     = new MemoryStream(bytes);
            var bitmap     = SKBitmap.Decode(stream);

            int width, height;

            //Считаем новые размеры исходя из оригенального размера
            if (bitmap.Width > bitmap.Height)
            {
                width  = size;
                height = bitmap.Height * size / bitmap.Width;
            }
            else
            {
                width  = bitmap.Width * size / bitmap.Height;
                height = size;
            }

            //Создаем картинку с новым размером
            using (var resized = bitmap?.Resize(new SKImageInfo(width, height), SKBitmapResizeMethod.Lanczos3))
            {
                if (resized == null)
                {
                    throw new Exception("Error resized.");
                }

                using (var image = SKImage.FromBitmap(resized))
                {
                    SKData encodedData = image.Encode(SKEncodedImageFormat.Jpeg, 100);

                    string folder    = Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures);
                    string filename  = $"{Guid.NewGuid()}.jpeg";
                    string imagePath = Path.Combine(FileSystem.CacheDirectory, filename);

                    var bitmapImageStream = File.Open(imagePath, FileMode.Create, FileAccess.Write, FileShare.None);

                    encodedData.SaveTo(bitmapImageStream);
                    bitmapImageStream.Flush(true);
                    bitmapImageStream.Dispose();

                    return(ImageSource.FromFile(imagePath));
                }
            }
        }
Esempio n. 23
0
        async Task <byte[]?> ITileSource.GetTileAsync(int x, int y, int z)
        {
            if (rasterProperties == null)
            {
                throw new InvalidOperationException("rasterProperties property is null.");
            }

            if (String.IsNullOrEmpty(this.configuration.ContentType))
            {
                throw new InvalidOperationException("configuration.ContentType property is null.");
            }

            if ((z < this.configuration.MinZoom) || (z > this.configuration.MaxZoom))
            {
                return(null);
            }
            else
            {
                var tileBounds      = U.WebMercator.GetTileBounds(x, U.WebMercator.FlipYCoordinate(y, z), z);
                var tileCoordinates = BuildTileCoordinatesList(this.rasterProperties, tileBounds);
                if (tileCoordinates.Count == 0)
                {
                    return(null);
                }

                var width  = U.WebMercator.TileSize;
                var height = U.WebMercator.TileSize;

                var imageInfo = new SKImageInfo(
                    width: width,
                    height: height,
                    colorType: SKColorType.Rgba8888,
                    alphaType: SKAlphaType.Premul);

                using var surface = SKSurface.Create(imageInfo);
                using var canvas  = surface.Canvas;
                canvas.Clear(new SKColor(0));

                DrawGeoTiffTilesToRasterCanvas(canvas, width, width, tileBounds, tileCoordinates, 0, this.rasterProperties.TileWidth, this.rasterProperties.TileHeight);

                var imageFormat = U.ImageHelper.SKEncodedImageFormatFromMediaType(this.configuration.ContentType);
                using SKImage image = surface.Snapshot();
                using SKData data   = image.Encode(imageFormat, 90); // TODO: pass quality parameter

                return(await Task.FromResult(data.ToArray()));
            }
        }
Esempio n. 24
0
        private async Task AnalyzePhotoMood(byte[] imageBytes)
        {
            var service = new CognitiveEmotionService();

            latestResult = await service.GetImageEmotions(imageBytes);

            var bitmap = SKBitmap.Decode(latestPhotoPath);
            var canvas = new SKCanvas(bitmap);

            var sbResult = new StringBuilder();

            for (var index = 0; index < latestResult.Length; index++)
            {
                var result = latestResult[index];
                var paint  = new SKPaint
                {
                    Style       = SKPaintStyle.Stroke,
                    Color       = SKColors.Red,
                    StrokeWidth = 5
                };
                var rect = result.FaceRectangle;

                canvas.DrawRect(SKRect.Create(rect.Left, rect.Top, rect.Width, rect.Height), paint);



                sbResult.Append(
                    $@"Face {index}\r\n
Happiness: {result.Scores.Happiness:P}
Neutral: {result.Scores.Neutral:P}
Contempt: {result.Scores.Contempt:P}
Fear: {result.Scores.Fear:P}
Disgust: {result.Scores.Disgust:P}
Sadness: {result.Scores.Sadness:P}
Anger: {result.Scores.Anger:P}
");
            }

            this.Result = sbResult.ToString();

            SKData d = SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Png, 100);

            this.ImageSource = Xamarin.Forms.ImageSource.FromStream(() =>
            {
                return(d.AsStream(true));
            });
        }
        internal static byte[] GetCaptcha(string captchaText)
        {
            byte[] imageBytes = null;

            int image2d_x = 0;
            int image2d_y = 0;

            SKRect size;

            int compensateDeepCharacters = 0;

            using (SKPaint drawStyle = CreatePaint())
            {
                compensateDeepCharacters = (int)drawStyle.TextSize / 5;
                if (System.StringComparer.Ordinal.Equals(captchaText, captchaText.ToUpperInvariant()))
                {
                    compensateDeepCharacters = 0;
                }

                size      = SkiaHelpers.MeasureText(captchaText, drawStyle);
                image2d_x = (int)size.Width + 10;
                image2d_y = (int)size.Height + 10 + compensateDeepCharacters;
            }

            using (SKBitmap image2d = new SKBitmap(image2d_x, image2d_y, SKColorType.Bgra8888, SKAlphaType.Premul))
            {
                using (SKCanvas canvas = new SKCanvas(image2d))
                {
                    canvas.DrawColor(SKColors.Black); // Clear

                    using (SKPaint drawStyle = CreatePaint())
                    {
                        canvas.DrawText(captchaText, 0 + 5, image2d_y - 5 - compensateDeepCharacters, drawStyle);
                    }
                    using (SKImage img = SKImage.FromBitmap(image2d))
                    {
                        using (SKData p = img.Encode(SKEncodedImageFormat.Png, 100))
                        {
                            imageBytes = p.ToArray();
                        }
                    }
                }
            }

            return(imageBytes);
        }
Esempio n. 26
0
        /// <summary>
        /// Create immutable bitmap from given stream.
        /// </summary>
        /// <param name="stream">Stream containing encoded data.</param>
        public ImmutableBitmap(Stream stream)
        {
            using (var skiaStream = new SKManagedStream(stream))
            {
                _image = SKImage.FromEncodedData(SKData.Create(skiaStream));

                if (_image == null)
                {
                    throw new ArgumentException("Unable to load bitmap from provided data");
                }

                PixelSize = new PixelSize(_image.Width, _image.Height);

                // TODO: Skia doesn't have an API for DPI.
                Dpi = new Vector(96, 96);
            }
        }
Esempio n. 27
0
        public static void RenderAndSave(int width = 600, int height = 400, int lineCount = 1_000)
        {
            var imageInfo = new SKImageInfo(width, height);
            var surface   = SKSurface.Create(imageInfo);

            RandomLines(surface, lineCount);

            string filePath = System.IO.Path.GetFullPath("demo.png");

            using (System.IO.Stream fileStream = System.IO.File.OpenWrite(filePath))
            {
                SKImage snap    = surface.Snapshot();
                SKData  encoded = snap.Encode(SKEncodedImageFormat.Png, 100);
                encoded.SaveTo(fileStream);
            }
            Console.WriteLine($"Saved: {filePath}");
        }
Esempio n. 28
0
        private async void HandlePaintCanvas(object sender, SKPaintSurfaceEventArgs e)
        {
            SKImageInfo info   = e.Info;
            SKCanvas    canvas = e.Surface.Canvas;

            canvas.Clear();
            if (_doSave)
            {
                using (var hole = new SKPath()) {
                    hole.AddCircle(info.Width / 2, info.Height / 2, info.Width / 3);
                    canvas.ClipPath(hole, antialias: true);
                }
            }
            canvas.SetMatrix(_m);
            //Draw ball image
            SKSize imgSize    = new SKSize(_bitmap.Width, _bitmap.Height);
            SKRect aspectRect = SKRect.Create(info.Width, info.Height).AspectFit(imgSize);

            canvas.DrawBitmap(_bitmap, aspectRect);
            if (!_doSave)
            {
                canvas.ResetMatrix();
                //Draw circle overlay
                using (var frame = new SKPath())
                    using (var hole = new SKPath()) {
                        frame.AddRect(info.Rect);
                        hole.AddCircle(info.Width / 2, info.Height / 2, info.Width / 3);
                        SKPath frameHole = frame.Op(hole, SKPathOp.Difference);
                        using (var p = new SKPaint {
                            IsAntialias = true, Style = SKPaintStyle.Fill, Color = new SKColor(128, 128, 128, 200)
                        }) {
                            canvas.DrawPath(frameHole, p);
                        }
                    }
            }
            else
            {
                SKImage snapI = e.Surface.Snapshot();
                snapI = snapI.Subset(canvas.DeviceClipBounds);
                SKData pngImage = snapI.Encode();
                File.WriteAllBytes(_ballFilename, pngImage.ToArray());
                await Navigation.PopAsync();

                OnBallImageUpdated(_ballFilename);
            }
        }
Esempio n. 29
0
        public static BitmapInfo LoadBitmap(object bitmapStream)
        {
            // todo: Our BitmapRegistry stores not only bitmaps. Perhaps we should store a class in it
            // which has all information. So we should have a SymbolImageRegistry in which we store a
            // SymbolImage. Which holds the type, data and other parameters.

            if (bitmapStream is string str)
            {
                if (str.ToLower().Contains("<svg"))
                {
                    var svg = new SKSvg();
                    svg.FromSvg(str);

                    return(new BitmapInfo {
                        Svg = svg
                    });
                }
            }

            if (bitmapStream is Stream stream)
            {
                if (stream.IsSvg())
                {
                    var svg = new 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);
        }
Esempio n. 30
0
        private string ChekeResult()
        {
            if (skimage == null)
            {
                return(null);
            }
            SKBitmap bitmap       = SKBitmap.FromImage(skimage);
            var      scaledBitmap = bitmap.Resize(new SKImageInfo(400, 400), SKBitmapResizeMethod.Triangle);

            skimage = SKImage.FromBitmap(scaledBitmap);
            bitmap  = SKBitmap.FromImage(skimage);

            SKData pngImage  = skimage.Encode();
            var    byteArray = pngImage.ToArray();
            Stream stream    = new MemoryStream(byteArray);

            ImageDim.Source = ImageSource.FromStream(() => { return(stream); });
            SKColor[]   arrColors = bitmap.Pixels;
            List <bool> boolImage = new List <bool>();

            foreach (var item in arrColors)
            {
                boolImage.Add(item.ToFormsColor() == Color.Black);
            }

            string answer = "no";
            double resultamountWeights = double.MinValue;

            foreach (var item in answers)
            {
                double amountWeights = 0.1;
                for (int i = 0; i < item.Weights.Count; i++)
                {
                    double valueImage = boolImage[i] ? 1 : 0;
                    amountWeights += valueImage * item.Weights[i];
                }
                if (resultamountWeights < amountWeights)
                {
                    resultamountWeights = amountWeights;
                    answer = item.Name;
                }
            }

            return(answer);
        }