async void OnButtonClicked(object sender, EventArgs args)
        {
            SKEncodedImageFormat imageFormat = (SKEncodedImageFormat)formatPicker.SelectedItem;
            int quality = (int)qualitySlider.Value;

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

                    if (data == null)
                    {
                        statusLabel.Text = "Encode returned null";
                    }
                    else if (data.Length == 0)
                    {
                        statusLabel.Text = "Encode returned empty array";
                    }
                    else
                    {
                        bool success = await DependencyService.Get <IPhotoLibrary>().
                                       SavePhotoAsync(data, folderNameEntry.Text, fileNameEntry.Text);

                        if (!success)
                        {
                            statusLabel.Text = "SavePhotoAsync return false";
                        }
                        else
                        {
                            statusLabel.Text = "Success!";
                        }
                    }
                }
        }
Exemple #2
0
 public bool Encode(SKWStream dst, SKEncodedImageFormat format, int quality)
 {
     using (new SKAutoLockPixels(this))
         using (var pixmap = new SKPixmap()) {
             return(PeekPixels(pixmap) && pixmap.Encode(dst, format, quality));
         }
 }
Exemple #3
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);
                    }
                }
            }
        }
Exemple #4
0
        private async Task UploadToAzure(Image dbImage, SKCodec codec, CloudBlobContainer container, int desiredWidth)
        {
            var ratio          = (float)desiredWidth / (float)codec.Info.Width;
            var supportedScale = codec.GetScaledDimensions(ratio);

            SKEncodedImageFormat target = codec.EncodedFormat == SKEncodedImageFormat.Gif ? SKEncodedImageFormat.Gif : SKEncodedImageFormat.Png;

            var width  = supportedScale.Width;
            var height = supportedScale.Height;
            var format = target.ToString();
            var name   = $"{dbImage.Slug}_{width}_{height}";

            var blobRef = container.GetBlockBlobReference(name);
            var url     = blobRef.StorageUri.PrimaryUri.ToString();

            using (var resultBitmap = SKBitmap.Decode(codec))
                using (var resizedBitmap = resultBitmap.Resize(new SKImageInfo(supportedScale.Width, supportedScale.Height), SKBitmapResizeMethod.Lanczos3))
                    using (var resultImage = SKImage.FromBitmap(resizedBitmap))
                        using (var imageStream = resultImage.Encode(target, 100).AsStream())
                        {
                            using (var outputSTream = await blobRef.OpenWriteAsync())
                            {
                                await imageStream.CopyToAsync(outputSTream);
                            }
                        }

            var data = new AzureAdapterMetadata(this.account.BlobEndpoint.ToString(), container.Name, name, url);

            await this.imageData.SetImageLinks(new ImageLink(dbImage.Id, null, width, height, format, ImageAdapter.AzureFile, data.ToString()));
        }
 /// <summary>
 /// Saves the specified file name.
 /// </summary>
 /// <param name="image">The image.</param>
 /// <param name="fileName">Name of the file.</param>
 /// <param name="format">The format.</param>
 /// <param name="quality">The quality.</param>
 public static void Save(this SKImage image, string fileName, SKEncodedImageFormat format = SKEncodedImageFormat.Png, int quality = 100)
 {
     using (var file = File.Create(fileName))
     {
         Save(image, file, format, quality);
     }
 }
Exemple #6
0
        public static SKData EncodeSvg(FsPath svgFile, int maxWidht, int maxHeight, SKEncodedImageFormat format = SKEncodedImageFormat.Png)
        {
            var svg = new SKSvg();

            svg.Load(svgFile.ToString());

            if (svg.Picture == null)
            {
                return(SKData.Empty);
            }

            SKRect svgSize = svg.Picture.CullRect;

            (int renderWidth, int renderHeight, float scale)sizeData = CalcNewSize(svgSize, maxWidht, maxHeight);

            var matrix = SKMatrix.CreateScale(sizeData.scale, sizeData.scale);

            using (SKBitmap bitmap = new SKBitmap(sizeData.renderWidth, sizeData.renderHeight))
            {
                using (SKCanvas canvas = new SKCanvas(bitmap))
                {
                    canvas.DrawPicture(svg.Picture, ref matrix);
                    canvas.Flush();
                }

                using (SKImage image = SKImage.FromBitmap(bitmap))
                {
                    return(image.Encode(format, 100));
                }
            }
        }
Exemple #7
0
        public static SKData EncodeImageToSKData(SKImage skImage, string format, int quality = 90)
        {
            SKEncodedImageFormat skFormat = SKEncodedImageFormat.Png;

            switch (format)
            {
            case "jpg":
                skFormat = SKEncodedImageFormat.Jpeg;
                break;

            case "jpeg":
                skFormat = SKEncodedImageFormat.Jpeg;
                break;

            case "gif":
                skFormat = SKEncodedImageFormat.Gif;
                break;

            case "bmp":
                skFormat = SKEncodedImageFormat.Bmp;
                break;

            case "webp":
                skFormat = SKEncodedImageFormat.Webp;
                break;

            default:
                skFormat = SKEncodedImageFormat.Png;
                break;
            }
            SKData skData = skImage.Encode(skFormat, quality);

            return(skData);
        }
Exemple #8
0
        async void OnSaveButtonClicked(object sender, EventArgs e)
        {
            SKEncodedImageFormat imageFormat = (SKEncodedImageFormat)formatPicker.SelectedItem;
            int quality = (int)qualitySlider.Value;

            using (MemoryStream memStream = new MemoryStream())
            {
                using (SKManagedWStream wstream = new SKManagedWStream(memStream))
                {
                    bool   result = pixmap.Encode(wstream, imageFormat, quality);
                    byte[] data   = memStream.ToArray();

                    if (data == null || data.Length == 0)
                    {
                        statusLabel.Text = "Encode failed";
                    }
                    else
                    {
                        bool success = await DependencyService.Get <IPhotoPickerService>().SavePhotoAsync(data, folderNameEntry.Text, fileNameEntry.Text);

                        if (!success)
                        {
                            statusLabel.Text = "Save failed";
                        }
                        else
                        {
                            statusLabel.Text = "Save succeeded";
                        }
                    }
                }
            }
        }
Exemple #9
0
 public static SKData EncodeToFormat(SKBitmap bitmap, SKEncodedImageFormat format, int quality = 100)
 {
     using (SKImage image = SKImage.FromBitmap(bitmap))
     {
         return(image.Encode(format, quality));
     }
 }
Exemple #10
0
 public bool Save(string path, SKColor background, SKEncodedImageFormat format = SKEncodedImageFormat.Png, int quality = 100, float scaleX = 1f, float scaleY = 1f)
 {
     using (var stream = System.IO.File.OpenWrite(path))
     {
         return(Save(stream, background, format, quality, scaleX, scaleY));
     }
 }
Exemple #11
0
        /// <summary>
        /// Exports the barcode image.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="format">Image export format.</param>
        /// <param name="quality">Image export qualty.</param>
        /// <exception cref="InvalidOperationException"></exception>
        public virtual void Export(string fileName, SKEncodedImageFormat format, int quality)
        {
            if (Image == null)
            {
                throw new InvalidOperationException("The barcode must be encoded before exported");
            }

            fileName = fileName.Replace("{barcode}", GetSafeFilename(Barcode));
            var path = Path.GetDirectoryName(fileName);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
#if NET6_0_OR_GREATER
            using var encodedImage = Image.Encode(format, quality);
            using var fileStream   = new FileStream(fileName, FileMode.OpenOrCreate);
            encodedImage.SaveTo(fileStream);
#else
            using (var encodedImage = Image.Encode(format, quality))
            {
                using (var fileStream = new FileStream(fileName, FileMode.OpenOrCreate))
                {
                    encodedImage.SaveTo(fileStream);
                }
            }
#endif
        }
Exemple #12
0
        public static async Task <string> SaveBitmap(SKBitmap bitmap, SKEncodedImageFormat format, int quality, string name, string folder)
        {
            using (MemoryStream memStream = new MemoryStream())
                using (SKManagedWStream wstream = new SKManagedWStream(memStream))
                {
                    bitmap.Encode(wstream, format, quality);
                    byte[] data = memStream.ToArray();

                    if (data == null || data.Length == 0)
                    {
                        throw new BitmapFileWriteException("Encode returned null or empty array");
                    }
                    else
                    {
                        /*string savedFilePath = Task.Run(() => DependencyService.Get<IPhotoLibrary>().
                         *  SavePhotoAsync(data, folder, name)).Result;*/

                        var savedFilePath = await DependencyService.Get <IPhotoLibrary>().SavePhotoAsync(data, folder, name);

                        //Task<string> result = task.Result();
                        //savedFilePath = await DependencyService.Get<IPhotoLibrary>().
                        //    SavePhotoAsync(data, folder, name);

                        //if (success)
                        //{
                        //    throw new BitmapFileWriteException("file save error");
                        //}
                        return(savedFilePath);
                    }
                }
        }
Exemple #13
0
 public SKData Encode(SKEncodedImageFormat encoder, int quality)
 {
     using (var stream = new SKDynamicMemoryWStream()) {
         var result = Encode(stream, this, encoder, quality);
         return(result ? stream.DetachAsData() : null);
     }
 }
Exemple #14
0
 /// <summary>
 /// Generates the image with given image properties
 /// </summary>
 /// <param name="captchaCode">Captcha code for which the image has to be generated</param>
 /// <param name="imageHeight">Height of the image to be generated</param>
 /// <param name="imageWidth">Width of the image to be generated</param>
 /// <param name="fontSize">Font size to be used</param>
 /// <param name="imageFormat">Image format to encode to</param>
 /// <param name="imageQuality">Image quality for encoding</param>
 /// <returns>Generated jpeg image as a MemoryStream object</returns>
 public static Stream GenerateImage(
     string captchaCode,
     int imageHeight, int imageWidth, int fontSize,
     SKEncodedImageFormat imageFormat = SKEncodedImageFormat.Jpeg, int imageQuality = 80
     ) => ImageFactory
 .BuildImage(captchaCode, imageHeight, imageWidth, fontSize)
 .Encode(imageFormat, imageQuality)
 .AsStream();
        public SaveImagePage()
        {
            InitializeComponent();
            SKEncodedImageFormat imageFormat = SKEncodedImageFormat.Png;

            fileNameEntry.Text = Path.ChangeExtension(fileNameEntry.Text, imageFormat.ToString());
            statusLabel.Text   = "OK";
        }
Exemple #16
0
 public async Task Write(SKImage image, string path, SKEncodedImageFormat format)
 {
     await Task.Run(() =>
     {
         using var output = File.OpenWrite(path);
         image.Encode(format, 80).SaveTo(output);
     });
 }
Exemple #17
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);
     }
 }
Exemple #18
0
 void OnFormatPickerChanged(object sender, EventArgs e)
 {
     if (formatPicker.SelectedIndex != -1)
     {
         SKEncodedImageFormat imageFormat = (SKEncodedImageFormat)formatPicker.SelectedItem;
         fileNameEntry.Text = Path.ChangeExtension(fileNameEntry.Text, imageFormat.ToString().ToLower());
     }
 }
Exemple #19
0
 private byte[] Convert(byte[] orig, SKEncodedImageFormat format)
 {
     using (var origBmp = SKBitmap.Decode(orig))
         using (var stream = new SKDynamicMemoryWStream())
         {
             origBmp.Encode(stream, format, 100);
             return(stream.DetachAsData().ToArray());
         }
 }
Exemple #20
0
        public bool Encode(SKWStream dst, SKEncodedImageFormat encoder, int quality)
        {
            if (dst == null)
            {
                throw new ArgumentNullException(nameof(dst));
            }

            return(SkiaApi.sk_pixmap_encode_image(dst.Handle, Handle, encoder, quality));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageHandle" /> class.
        /// </summary>
        /// <param name="path">Path of the loaded image</param>
        /// <param name="image">Loaded image data</param>
        /// <param name="format">Format of the image</param>
        public ImageHandle(string path, SKBitmap image, SKEncodedImageFormat format)
        {
            Guard.Against.ArgumentNullOrEmpty(path, "path");
            Guard.Against.ArgumentNull(image, "image");

            OriginalImage     = image;
            LoadingSettings   = new ImageDefaults(path, image.Width, image.Height, image.Info.BytesSize64, format.ToAppFormat());
            ManipulationState = new ManipulationState();
        }
 public static Stream ToStream(SKBitmap bitmap, SKEncodedImageFormat imageFormat, int quality)
 {
     using (var image = SKImage.FromBitmap(bitmap))
     {
         var    encodedImage = image.Encode(imageFormat, quality);
         Stream output       = encodedImage.AsStream();
         return(output);
     }
 }
Exemple #23
0
        public InputImageParameters(string contentType, SKEncodedImageFormat format, double minimumDifference, string uploadUrl)
        {
            OutputContentType = contentType;
            Format            = format;
            MinimumDifference = minimumDifference;
            UploadUrl         = uploadUrl;

            InputStream = null;
        }
Exemple #24
0
    public InternalCaptchaGenerator(IOptionsMonitor <DrawingExtensionOptions> options)
    {
        _options         = options.CurrentValue;
        _imageFormat     = _options.ImageFormat.AsEncodedImageFormat();
        _backgroundColor = _options.Colors.Background.AsColor();

        _forePaint   = _options.Watermark.Font.CreatePaint(_options.Colors.Fore);
        _alternPaint = _options.Watermark.Font.CreatePaint(_options.Colors.Alternate);
        _noisePaint  = _options.Captcha.BackgroundNoise.CreatePaint(_options.Colors.Interference);
    }
Exemple #25
0
        public static MemoryStream Write(this SKBitmap bitmap, SKEncodedImageFormat fmt = SKEncodedImageFormat.Png, int quality = 100)
        {
            var memStream = new MemoryStream();

            using var wstream = new SKManagedWStream(memStream);

            bitmap.Encode(wstream, fmt, quality);
            memStream.Position = 0;
            return(memStream);
        }
Exemple #26
0
        public bool Encode(Stream dst, SKEncodedImageFormat encoder, int quality)
        {
            if (dst == null)
            {
                throw new ArgumentNullException(nameof(dst));
            }

            using var wrapped = new SKManagedWStream(dst);
            return(Encode(wrapped, encoder, quality));
        }
Exemple #27
0
        public bool Encode(SKWStream dst, SKEncodedImageFormat format, int quality)
        {
            if (dst == null)
            {
                throw new ArgumentNullException(nameof(dst));
            }

            using var pixmap = PeekPixels();
            return(pixmap?.Encode(dst, format, quality) ?? false);
        }
Exemple #28
0
        private void ProcessImage(FsPath file, RuntimeSettings settings, FsPath targetdir, ILog log)
        {
            var options = settings.CurrentBuildConfig.ImageOptions;

            if (!ImageUtils.IsImage(file))
            {
                log.Info("Unknown image format, skipping: {0}", file);
                return;
            }

            if (ImageUtils.IsSvg(file))
            {
                log.Detail("Rendering SVG: {0}", file);
                SKEncodedImageFormat format = SKEncodedImageFormat.Png;

                if (options.EncodeSvgAsWebp)
                {
                    format = SKEncodedImageFormat.Webp;
                }

                using (var data = ImageUtils.EncodeSvg(file, options.MaxWidth, options.MaxHeight, format))
                {
                    InlineOrSave(file, targetdir, log, settings, data, ".png");
                    return;
                }
            }

            log.Detail("Processing image: {0}", file);
            using (SKBitmap image = ImageUtils.LoadImage(file))
            {
                var format = ImageUtils.GetSkiaImageFormat(file);
                using (SKBitmap resized = ImageUtils.ResizeIfBigger(image, options.MaxWidth, options.MaxHeight))
                {
                    if ((format == SKEncodedImageFormat.Jpeg && options.RecodeJpegToWebp) ||
                        (format == SKEncodedImageFormat.Png && options.RecodePngToWebp))
                    {
                        using SKData webp = ImageUtils.EncodeToFormat(resized,
                                                                      SKEncodedImageFormat.Webp,
                                                                      options.ImageQuality);

                        InlineOrSave(file, targetdir, log, settings, webp, ".webp");
                    }
                    else if (format == SKEncodedImageFormat.Jpeg)
                    {
                        using SKData data = ImageUtils.EncodeToFormat(resized, format, options.ImageQuality);
                        InlineOrSave(file, targetdir, log, settings, data);
                    }
                    else
                    {
                        using SKData data = ImageUtils.EncodeToFormat(resized, format);
                        InlineOrSave(file, targetdir, log, settings, data);
                    }
                }
            }
        }
 /// <summary>
 /// Saves the specified stream.
 /// </summary>
 /// <param name="image">The image.</param>
 /// <param name="stream">The stream.</param>
 /// <param name="format">The format.</param>
 /// <param name="quality">The quality.</param>
 /// <exception cref="ArgumentOutOfRangeException">quality</exception>
 public static void Save(this SKImage image, Stream stream, SKEncodedImageFormat format = SKEncodedImageFormat.Png, int quality = 100)
 {
     if (quality < 1 || quality > 100)
     {
         throw new ArgumentOutOfRangeException(nameof(quality));
     }
     using (var data = image.Encode(format, quality))
     {
         data.SaveTo(stream);
     }
 }
Exemple #30
0
 public static void SaveBitmap(
     [InputPin(PropertyMode = PropertyMode.Never)] SKBitmap bitmap,
     [InputPin(PropertyMode = PropertyMode.Default, ResolvePath = true)] string path,
     [InputPin(PropertyMode = PropertyMode.Default)] SKEncodedImageFormat format = SKEncodedImageFormat.Png,
     [InputPin(PropertyMode = PropertyMode.Default)] int quality = 95
     )
 {
     using (var stream = new SKFileWStream(path))
     {
         SKPixmap.Encode(stream, bitmap, format, quality);
     }
 }