/// <inheritdoc cref="SaveAsPng(QrCode, string, int, int)"/>
 /// <param name="background">The background color.</param>
 /// <param name="foreground">The foreground color.</param>
 public static void SaveAsPng(this QrCode qrCode, string filename, int scale, int border, SKColor foreground, SKColor background)
 {
     using SKBitmap bitmap   = qrCode.ToBitmap(scale, border, foreground, background);
     using SKData data       = bitmap.Encode(SKEncodedImageFormat.Png, 90);
     using FileStream stream = File.OpenWrite(filename);
     data.SaveTo(stream);
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Crop a file
        /// </summary>
        /// <param name="source"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="dest"></param>
        /// <returns></returns>
        public Task CropImage(FileInfo source, int x, int y, int width, int height, Stream destStream)
        {
            Stopwatch watch = new Stopwatch("SkiaSharpCrop");

            try
            {
                using SKBitmap sourceBitmap = SKBitmap.Decode(source.FullName);

                // setup crop rect
                var cropRect = new SKRectI(x, y, x + width, y + height);
                var cropped  = Crop(sourceBitmap, cropRect);
                using SKData data = cropped.Encode(SKEncodedImageFormat.Jpeg, 90);
                data.SaveTo(destStream);
            }
            catch (Exception ex)
            {
                Logging.LogError($"Exception during Skia Crop processing: {ex.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 3
0
        static void TestDrawUnderline(string text, float fontSize, TextFormatFlags flags)
        {
            var font = new Font(Typeface, fontSize, FontStyle.Underline);

            var fileName = CleanFileName($"underline-{text}-{fontSize}-{flags}.png");

            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            {
                fileName = fileName.Replace(c, '_');
            }

            var size       = TextRendererSk.MeasureText(text, font, 0, flags);
            var BackColour = SKColors.Black;

            using (SKBitmap bitmap = new SKBitmap((int)size.Width, (int)size.Height, SKColorType.Rgba8888, SKAlphaType.Unpremul))
                using (var canvas = new SKCanvas(bitmap))
                {
                    canvas.Clear(BackColour);

                    TextRendererSk.DrawText(canvas, text, font, SKRect.Create(0, -1, size.Width, size.Height), SKColors.White, flags);

                    using (Stream s = File.Open(fileName, FileMode.Create))
                    {
                        SKData d = SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Png, 100);
                        d.SaveTo(s);
                    }
                }

            Console.WriteLine("Drawing Underline {0} (fontSize {1}, flags {2}), measured size: {3}", text, fontSize, flags, size);
        }
Ejemplo n.º 4
0
        public async Task <bool> SaveSnapshot(Stream outputFilestream, int thumbnailSize = -1)
        {
            ClearComponent();

            if (_thumbnailData != null)
            {
                _thumbnailData.Dispose();
                _thumbnailData = null;
            }

            _thumbnailSize      = thumbnailSize;
            _saveSurface        = true;
            thumbnailCompletion = new TaskCompletionSource <bool>();

            _canvas.InvokeInvalidate();

            // wait for the canvas to draw itself.  thumbnail bitmap needs to be set during the draw portion
            await thumbnailCompletion.Task;

            bool result = true;

            try
            {
                _thumbnailData.SaveTo(outputFilestream);
                _thumbnailData.Dispose();
                _thumbnailData = null;
            }
            catch (Exception)
            {
                result = false;
            }
            return(result);
        }
Ejemplo n.º 5
0
        async Task GenerateFunction(int lut_size)
        {
            SKData data = new SKData();
            //Task.Run(() => {

            var     image = Hald.GenerateClutImage(lut_size);
            SKImage img   = SKImage.FromBitmap(image);

            data = img.Encode(SKImageEncodeFormat.Png, 90);


            //  });



            SaveFileDialog savefile = new SaveFileDialog();

            savefile.FileName = string.Format("identity_{0}.png", lut_size);
            savefile.Filter   = "PNG files (*.png)|*.png";
            if (savefile.ShowDialog() == true)
            {
                using (FileStream fs = new FileStream(savefile.FileName, FileMode.Create))
                {
                    data.SaveTo(fs);
                }
            }
            EndAnimate();
        }
Ejemplo n.º 6
0
        public static void SaveToFile(this SKImage bitmap, String sFileName)
        {
            SKEncodedImageFormat imageFormat = SKEncodedImageFormat.Png;
            int quality = (int)100;

            using (MemoryStream memStream = new MemoryStream())
            {
                SKData skd = bitmap.Encode(imageFormat, quality);
                skd.SaveTo(memStream);
                byte[] data = memStream.ToArray();

                if (data == null)
                {
                    return;
                }
                else if (data.Length == 0)
                {
                    return;
                }
                else
                {
                    using (StreamWriter sw = new StreamWriter(new FileStream(sFileName, FileMode.Create)))
                    {
                        sw.Write(data);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public async Task <string> GetStitchedBitmapSource(int playlistId, int width = 300, bool asThumbnail = false)
        {
            if (playlistId > 0)
            {
                string fileName = $"{playlistId}_{width}.{ImageExtension}";
                if (!_storageService.TryToGetImagePath(fileName, out string fullName))
                {
                    int height = width;

                    ObservableCollection <Guid> albumIds = await GetImageIds(playlistId);

                    SKImage stitchedImage = await Combine(albumIds, width, height, asThumbnail);

                    using (SKData encoded = stitchedImage.Encode(SKEncodedImageFormat.Png, 100))
                    {
                        using (System.IO.Stream outFile = System.IO.File.OpenWrite(fullName))
                        {
                            encoded.SaveTo(outFile);
                        }
                    }
                }
                return(fullName);
            }
            return(null);
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            Random rand = new Random();

            // set up the image
            SKImageInfo imageInfo = new SKImageInfo(800, 600, SKColorType.Rgb888x, SKAlphaType.Premul);
            SKSurface   surface   = SKSurface.Create(imageInfo);
            SKCanvas    canvas    = surface.Canvas;

            // draw some lines
            canvas.Clear(SKColor.Parse("#003366"));
            var paint = new SKPaint
            {
                Color       = new SKColor(255, 255, 255, 123),
                IsAntialias = true
            };

            for (int i = 0; i < 1000; i++)
            {
                SKPoint ptA = new SKPoint(rand.Next(imageInfo.Width), rand.Next(imageInfo.Height));
                SKPoint ptB = new SKPoint(rand.Next(imageInfo.Width), rand.Next(imageInfo.Height));
                canvas.DrawLine(ptA, ptB, paint);
            }

            // save the output
            string filename = System.IO.Path.GetFullPath("test.png");

            System.IO.Stream fileStream = System.IO.File.OpenWrite(filename);
            SKImage          snap       = surface.Snapshot();
            SKData           encoded    = snap.Encode(SKEncodedImageFormat.Png, 100);

            encoded.SaveTo(fileStream);
            Console.WriteLine($"Saved: {filename}");
        }
Ejemplo n.º 9
0
        static void TestDrawSelectionMultiline(string text, float fontSize, TextFormatFlags flags, TextPaintOptions options)
        {
            var font = new Font(Typeface, fontSize);

            var fileName = CleanFileName($"DrawSelectionMultiline-start({options.SelectionStart})-end({options.SelectionEnd})-{text}-{fontSize}-{flags}.png");

            var size       = TextRendererSk.MeasureText(text, font, 0, flags);
            var BackColour = SKColors.Black;

            using (SKBitmap bitmap = new SKBitmap((int)size.Width, (int)size.Height, SKColorType.Rgba8888, SKAlphaType.Unpremul))
                using (var canvas = new SKCanvas(bitmap))
                {
                    canvas.Clear(BackColour);

                    TextRendererSk.DrawText(canvas, text, font, SKRect.Create(0, 0, size.Width, size.Height), SKColors.White, flags, options);

                    using (Stream s = File.Open(fileName, FileMode.Create))
                    {
                        SKData d = SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Png, 100);
                        d.SaveTo(s);
                    }
                }

            Console.WriteLine("Drawing with selection and multiline {0} (fontSize {1}, flags {2}), measured size: {3}", text, fontSize, flags, size);
        }
Ejemplo n.º 10
0
        public async ValueTask <byte[]> GetBytesWithFilterAsync(
            int size,
            string topic = null,
            SKImageFilter imageFilter = null,
            SKColorFilter colorFilter = null,
            SKShader shader           = null,
            SKBlendMode blendMode     = SKBlendMode.Overlay)
        {
            Trace.WriteLine("Start");
            string url;

            if (string.IsNullOrEmpty(topic))
            {
                url = string.Format(URL_PATTERN_RND, size);
            }
            else
            {
                url = string.Format(URL_PATTERN, size, topic);
            }

            var imageInfo = new SKImageInfo(size, size);

            using (var http = new HttpClient())
            {
                var image = await http.GetByteArrayAsync(url);//.ConfigureAwait(false);

                Trace.WriteLine("Downloaded");
                using (var outStream = new MemoryStream())
                    using (var bitmap = SKBitmap.Decode(image, imageInfo))
                        using (var surface = SKSurface.Create(imageInfo))
                            using (var paint = new SKPaint())
                            {
                                SKCanvas canvas = surface.Canvas;
                                canvas.DrawColor(SKColors.White);
                                if (imageFilter != null)
                                {
                                    paint.ImageFilter = imageFilter;
                                }
                                if (colorFilter != null)
                                {
                                    paint.ColorFilter = colorFilter;
                                }

                                // draw the bitmap through the filter
                                var rect = SKRect.Create(imageInfo.Size);
                                canvas.DrawBitmap(bitmap, rect, paint);
                                if (shader != null)
                                {
                                    paint.Shader    = shader;
                                    paint.BlendMode = blendMode;
                                    canvas.DrawPaint(paint);
                                }
                                SKData data = surface.Snapshot().Encode(SKEncodedImageFormat.Jpeg, 80);
                                data.SaveTo(outStream);
                                byte[] manipedImage = outStream.ToArray();
                                Trace.WriteLine("End");
                                return(manipedImage);
                            }
            }
        }
Ejemplo n.º 11
0
 public static void saveBitmap(SKBitmap bitmap, string path, SKEncodedImageFormat encoding)
 {
     path = Path.ChangeExtension(path, encoding.ToString().ToLower());
     using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) {
         SKData data = SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Jpeg, 100);
         data.SaveTo(fs);
     }
 }
Ejemplo n.º 12
0
        void SavePngImage(SKImage image, string fileName)
        {
            SKData data = image.Encode(SKEncodedImageFormat.Png, 100);

            using (FileStream stream = new FileStream(fileName, FileMode.Create))
            {
                data.SaveTo(stream);
            }
        }
Ejemplo n.º 13
0
        void SaveJpegImage(SKImage image, string fileName)
        {
            SKData data = image.Encode(SKEncodedImageFormat.Jpeg, jpegQuality);

            using (FileStream stream = new FileStream(fileName, FileMode.Create))
            {
                data.SaveTo(stream);
            }
        }
Ejemplo n.º 14
0
        private string TextWatermark(string filePath)
        {
            SKImage finalImage;
            string  markedImagePath = string.Empty;

            SKBitmap pic = SKBitmap.Decode(filePath);

            using (var tempSurface = SKSurface.Create(new SKImageInfo(pic.Width, pic.Height)))
            {
                //get the drawing canvas of the surface
                var canvas = tempSurface.Canvas;

                //set background color
                canvas.Clear(SKColors.Transparent);

                //go through each image and draw it on the final image
                int offset    = 0;
                int offsetTop = 0;

                canvas.DrawBitmap(pic, SKRect.Create(offset, offsetTop, pic.Width, pic.Height));


                SKPaint paint = new SKPaint
                {
                    Color    = SKColors.LightGreen,
                    TextSize = 50
                };

                SKPoint offsetPoint = new SKPoint
                {
                    X = pic.Width / 20,
                    Y = pic.Height * 9.5f / 10
                };

                SKPath path = new SKPath();

                canvas.DrawTextOnPath(watermarkTextEntry.Text, path, offsetPoint, paint);

                //canvas.DrawBitmap(stamp, SKRect.Create(offset, pic.Height, 100, 100));

                ///

                // return the surface as a manageable image
                finalImage = tempSurface.Snapshot();
            }

            //save the new image
            using (SKData encoded = finalImage.Encode(SKEncodedImageFormat.Png, 100))
                using (Stream outFile = File.OpenWrite("storage/emulated/0/Android/data/com.companyname.Forms/files/Pictures/Sample/final.jpg"))
                {
                    encoded.SaveTo(outFile);
                    image.Source    = ImageSource.FromFile("storage/emulated/0/Android/data/com.companyname.Forms/files/Pictures/Sample/final.jpg");
                    markedImagePath = "storage/emulated/0/Android/data/com.companyname.Forms/files/Pictures/Sample/final.jpg";
                }
            return(markedImagePath);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Resize using SkiaSharp - this can do 100 images in about 30s (2020 i5 MacBook Air).
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destFiles"></param>
        public void CreateThumbs(FileInfo source, IDictionary <FileInfo, ThumbConfig> destFiles, out string imageHash)
        {
            try
            {
                int desiredWidth = destFiles.Max(x => x.Value.width);

                using var sourceBitmap = LoadOrientedBitmap(source, desiredWidth);

                imageHash = GetHash(sourceBitmap);

                Stopwatch thumbs = new Stopwatch("SkiaSharpThumbs");

                // Dropping this from High to Low doesn't have that much of an effect
                // in terms of performance.
                var quality   = SKFilterQuality.Low;
                var srcBitmap = sourceBitmap;

                foreach (var pair in destFiles.OrderByDescending(x => x.Value.width))
                {
                    var dest   = pair.Key;
                    var config = pair.Value;

                    float widthScaleFactor = (float)srcBitmap.Width / (float)config.width;
                    float heighScaleFactor = (float)srcBitmap.Height / (float)config.height;
                    float scaleFactor      = Math.Min(widthScaleFactor, heighScaleFactor);

                    using var scaledImage = new SKBitmap((int)(srcBitmap.Width / scaleFactor), (int)(srcBitmap.Height / scaleFactor));
                    srcBitmap.ScalePixels(scaledImage.PeekPixels(), quality);

                    var cropSize = new SKSize {
                        Height = config.height, Width = config.width
                    };
                    using var cropped = config.cropToRatio ? Crop(scaledImage, cropSize) : scaledImage;

                    using SKData data = cropped.Encode(SKEncodedImageFormat.Jpeg, 90);

                    using (var stream = new FileStream(dest.FullName, FileMode.Create, FileAccess.Write))
                        data.SaveTo(stream);

                    // Now, use the previous scaled image as the basis for the
                    // next smaller thumbnail. This should reduce processing
                    // time as we only work on the large image on the first
                    // iteration
                    srcBitmap = scaledImage.Copy();

                    // TODO: Dispose
                }

                thumbs.Stop();
            }
            catch (Exception ex)
            {
                Logging.Log($"Exception during Skia processing: {ex.Message}");
                throw;
            }
        }
        ISerializableObject ImageFromSKData(SKData data, int width, int height)
        {
            byte [] pngData;
            using (var ms = new MemoryStream()) {
                data.SaveTo(ms);
                pngData = ms.ToArray();
            }

            return(new Image(ImageFormat.Png, pngData, width, height));
        }
Ejemplo n.º 17
0
        public static void SaveBitmap(SKBitmap bitmap, string filename)
        {
            // Make sure the directories exist
            Directory.CreateDirectory(Path.GetDirectoryName(filename));

            using (SKImage image = SKImage.FromBitmap(bitmap))
                using (SKData data = image.Encode(SKImageEncodeFormat.Png, 100))
                    using (Stream stream = File.OpenWrite(filename))
                    {
                        data.SaveTo(stream);
                    }
        }
        public void Missisippi_Skia(int offset)
        {
            string jsonContent = File.ReadAllText(TestFile.GetInputFileFullPath(TestImages.GeoJson.States));

            FeatureCollection features = JsonConvert.DeserializeObject <FeatureCollection>(jsonContent);

            Feature missisipiGeom = features.Features.Single(f => (string)f.Properties["NAME"] == "Mississippi");

            Matrix3x2 transform = Matrix3x2.CreateTranslation(-87, -54)
                                  * Matrix3x2.CreateScale(60, 60)
                                  * Matrix3x2.CreateTranslation(offset, offset);
            IReadOnlyList <PointF[]> points = PolygonFactory.GetGeoJsonPoints(missisipiGeom, transform);

            var path = new SKPath();

            foreach (PointF[] pts in points.Where(p => p.Length > 2))
            {
                path.MoveTo(pts[0].X, pts[0].Y);

                for (int i = 0; i < pts.Length; i++)
                {
                    path.LineTo(pts[i].X, pts[i].Y);
                }

                path.LineTo(pts[0].X, pts[0].Y);
            }

            var imageInfo = new SKImageInfo(10000, 10000);

            using var paint = new SKPaint
                  {
                      Style       = SKPaintStyle.Stroke,
                      Color       = SKColors.White,
                      StrokeWidth = 1f,
                      IsAntialias = true,
                  };

            using var surface = SKSurface.Create(imageInfo);
            SKCanvas canvas = surface.Canvas;

            canvas.Clear(new SKColor(0, 0, 0));
            canvas.DrawPath(path, paint);

            string outDir = TestEnvironment.CreateOutputDirectory("Skia");
            string fn     = System.IO.Path.Combine(outDir, $"Missisippi_Skia_{offset}.png");

            using SKImage image = surface.Snapshot();
            using SKData data   = image.Encode(SKEncodedImageFormat.Png, 100);

            using FileStream fs = File.Create(fn);
            data.SaveTo(fs);
        }
Ejemplo n.º 19
0
        public static void SaveImage(Image img, string path)
        {
            if (img == null || path == null)
            {
                return;
            }
            SKImage image = SKImage.FromBitmap(img);
            SKData  png   = image.Encode(SKEncodedImageFormat.Png, 100);

            using (var filestream = File.OpenWrite(path))
            {
                png.SaveTo(filestream);
            }
        }
Ejemplo n.º 20
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);
            }
        }
Ejemplo n.º 21
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());
                }
            }
        }
Ejemplo 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));
                }
            }
        }
Ejemplo n.º 23
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}");
        }
Ejemplo n.º 24
0
        public async Task ResizeImagesAsync(string sourcePath, string destPath, double scale, CancellationToken token)
        {
            if (!Directory.Exists(destPath))
            {
                Directory.CreateDirectory(destPath);
            }

            var         allFiles = FindImages(sourcePath);
            List <Task> taskList = new List <Task>();

            foreach (var filePath in allFiles)
            {
                Task t = Task.Run(() => {
                    // if (token.IsCancellationRequested) {
                    //     Console.WriteLine("他媽不幹了");
                    //     return ;
                    // }
                    token.ThrowIfCancellationRequested();

                    Console.WriteLine("TID\t" + Thread.GetCurrentProcessorId());
                    SKBitmap bitmap  = SKBitmap.Decode(filePath);
                    SKImage imgPhoto = SKImage.FromBitmap(bitmap);
                    string imgName   = Path.GetFileNameWithoutExtension(filePath);

                    int sourceWidth  = imgPhoto.Width;
                    int sourceHeight = imgPhoto.Height;

                    int destinationWidth  = (int)(sourceWidth * scale);
                    int destinationHeight = (int)(sourceHeight * scale);
                    Console.WriteLine(imgName + ".jpg" + " Save TID\t" + Thread.GetCurrentProcessorId());
                    using SKBitmap scaledBitmap = bitmap.Resize(
                              new SKImageInfo(destinationWidth, destinationHeight),
                              SKFilterQuality.High);
                    using SKImage scaledImage = SKImage.FromBitmap(scaledBitmap);
                    using SKData data         = scaledImage.Encode(SKEncodedImageFormat.Jpeg, 100);
                    using FileStream s        = File.OpenWrite(Path.Combine(destPath, imgName + ".jpg"));
                    data.SaveTo(s);
                    Console.WriteLine(imgName + ".jpg" + " Async done with TID\t" + Thread.GetCurrentProcessorId());
                });

                taskList.Add(t);
            }

            await Task.WhenAll(taskList);
        }
Ejemplo n.º 25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="image"></param>
        /// <param name="title"></param>
        public void SaveTempImage(SKData image, string title)
        {
            string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string path      = Path.Combine(docFolder, title);

            using (var memoryStream = new MemoryStream())
            {
                image.SaveTo(memoryStream);

                NSData  appleData = NSData.FromArray(memoryStream.ToArray());
                UIImage appleImg  = UIImage.LoadFromData(appleData);

                appleImg.SaveToPhotosAlbum((img, error) => {
                    var o = img as UIImage;
                    Console.WriteLine("error:" + error);
                });
            }
        }
Ejemplo n.º 26
0
        public async ValueTask <IActionResult> GetMergeAsync(
            int size, string topic = null)
        {
            Task <byte[]> t1 = DoManipAsync();
            Task <byte[]> t2 = DoManipAsync();

            async Task <byte[]> DoManipAsync()
            {
                using (var filter = SKImageFilter.CreateBlur(5, 5))
                {
                    var result = await GetBytesWithFilterAsync(size, topic, filter);//.ConfigureAwait(false);

                    return(result);
                }
            }

            var results = await Task.WhenAll(t1, t2).ConfigureAwait(false);

            var imageInfo = new SKImageInfo(size, size);
            var mergeInfo = new SKImageInfo(size * 2, size);

            using (var outStream = new MemoryStream())
                using (var bitmap0 = SKBitmap.Decode(results[0], imageInfo))
                    using (var bitmap1 = SKBitmap.Decode(results[1], imageInfo))
                        using (var surface = SKSurface.Create(mergeInfo))
                            using (var paint = new SKPaint())
                            {
                                SKCanvas canvas = surface.Canvas;
                                canvas.DrawColor(SKColors.White);


                                // draw the bitmap through the filter
                                var rect = SKRect.Create(imageInfo.Size);
                                canvas.DrawBitmap(bitmap0, rect, paint);
                                rect = SKRect.Create(size, 0, size, size);
                                canvas.DrawBitmap(bitmap1, rect, paint);

                                SKData data = surface.Snapshot().Encode(SKEncodedImageFormat.Jpeg, 80);
                                data.SaveTo(outStream);
                                byte[] manipedImage = outStream.ToArray();
                                var    response     = File(manipedImage, MEDIA_TYPE);
                                return(response);
                            }
        }
Ejemplo n.º 27
0
        public void Save(string filePath, int width = 640, int height = 480, int quality = 95)
        {
            filePath = System.IO.Path.GetFullPath(filePath);

            var info = new SKImageInfo(width, height);

            using (SKSurface surface = SKSurface.Create(info))
            {
                Render(surface.Canvas);
                using (System.IO.Stream fileStream = System.IO.File.OpenWrite(filePath))
                {
                    // TODO: support BMP, PNG, TIF, GIF, and JPG
                    SKImage snap    = surface.Snapshot();
                    SKData  encoded = snap.Encode(SKEncodedImageFormat.Png, quality);
                    encoded.SaveTo(fileStream);
                    Debug.WriteLine($"Wrote: {filePath}");
                }
            }
        }
Ejemplo n.º 28
0
        public static void RenderSvg(SKSvg svg, Stream outStream, SKEncodedImageFormat skFormat, int minSize,
                                     int multiplier)
        {
            SKRect svgSize   = svg.Picture.CullRect;
            float  svgMax    = Math.Max(svgSize.Width, svgSize.Height);
            float  canvasMin = minSize * multiplier;
            float  scale     = canvasMin / svgMax;
            var    matrix    = SKMatrix.CreateScale(scale, scale);
            var    bitmap    = new SKBitmap((int)(svgSize.Width * scale), (int)(svgSize.Height * scale));
            var    canvas    = new SKCanvas(bitmap);

            canvas.Clear();
            canvas.DrawPicture(svg.Picture, ref matrix);
            canvas.Flush();
            var    image = SKImage.FromBitmap(bitmap);
            SKData data  = image.Encode(skFormat, 100);

            data.SaveTo(outStream);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Image Resize Async method using skiasharp wrapper
        /// </summary>
        /// <param name="sourceBitmap"></param>
        /// <param name="maxWidth"></param>
        /// <param name="maxHeight"></param>
        /// <param name="quality"></param>
        /// <returns>Resized SKBitmap with given parameter</returns>
        public async Task <MemoryStream> Resize(byte[] byte_image, int maxWidth, int maxHeight, SKFilterQuality quality = SKFilterQuality.Medium)
        {
            var      bitmap       = SKBitmap.Decode(byte_image);
            int      height       = Math.Min(maxHeight, bitmap.Height);
            int      width        = Math.Min(maxWidth, bitmap.Width);
            SKBitmap scaledBitmap = null;
            await Task.Run(() =>
            {
                scaledBitmap = bitmap.Resize(new SKImageInfo(width, height), quality);
            });

            using SKImage img       = SKImage.FromBitmap(scaledBitmap);
            using SKData new_bitmap = img.Encode(SKEncodedImageFormat.Png, 100);
            MemoryStream ms = new MemoryStream();

            new_bitmap.SaveTo(ms);

            return(ms);
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            SKImageInfo info = new SKImageInfo(640, 480, SKColorType.Bgra8888, SKAlphaType.Premul);

            using (SKBitmap bmp = new SKBitmap(info))
            {
                using (SKCanvas canvas = new SKCanvas(bmp))
                {
                    canvas.Clear(SKColors.Transparent);
                    using (SKPaint paint = new SKPaint())
                    {
                        paint.IsAntialias = true;
                        paint.Color       = SKColors.Red;
                        canvas.DrawCircle(100, 100, 100, paint);
                    }
                }
                using (SKImage img = SKImage.FromBitmap(bmp))
                    using (SKData data = img.Encode(SKEncodedImageFormat.Png, 100))
                        using (System.IO.FileStream fout = System.IO.File.OpenWrite("test.png"))
                        {
                            data.SaveTo(fout);
                        }
            }
            using (SKBitmap bmp = new SKBitmap(info))
            {
                using (SKCanvas canvas = new SKCanvas(bmp))
                {
                    canvas.Clear(SKColors.Transparent);
                    using (SKPaint paint = new SKPaint())
                    {
                        paint.IsAntialias = true;
                        paint.Color       = SKColors.Blue;
                        canvas.DrawRect(50, 50, 200, 200, paint);
                    }
                }
                using (SKImage img = SKImage.FromBitmap(bmp))
                    using (SKData data = img.Encode(SKEncodedImageFormat.Png, 100))
                        using (System.IO.FileStream fout = System.IO.File.OpenWrite("test1.png"))
                        {
                            data.SaveTo(fout);
                        }
            }
        }