예제 #1
0
        public static System.Drawing.Bitmap Lines(SKSurface surface, int count)
        {
            float width  = surface.Canvas.LocalClipBounds.Width;
            float height = surface.Canvas.LocalClipBounds.Height;

            surface.Canvas.DrawColor(new SKColor(0, 0, 0));

            var paint = new SKPaint();

            paint.IsAntialias = true;

            Random rand = new Random();

            for (int i = 0; i < count; i++)
            {
                paint.Color = new SKColor((byte)rand.Next(255), (byte)rand.Next(255), (byte)rand.Next(255));
                SKPoint pt0 = new SKPoint((float)(rand.NextDouble() * width), (float)(rand.NextDouble() * height));
                SKPoint pt1 = new SKPoint((float)(rand.NextDouble() * width), (float)(rand.NextDouble() * height));
                surface.Canvas.DrawLine(pt0, pt1, paint);
            }

            SKImage      image   = surface.Snapshot();
            SKData       data    = image.Encode(SKEncodedImageFormat.Png, 100);
            MemoryStream mStream = new MemoryStream(data.ToArray());

            var bmp = new System.Drawing.Bitmap(mStream, false);

            return(bmp);
        }
예제 #2
0
        private void Save_Click(object sender, EventArgs e)
        {
            if (skimage == null)
            {
                return;
            }
            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);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            using (SKSurface surface = SKSurface.Create(make_image(500, 500)))
            {
                SKCanvas canvas = surface.Canvas;

                canvas.Clear(SKColors.Red);

                using (SKPaint paint = new SKPaint())
                {
                    paint.Color       = SKColors.Blue;
                    paint.IsAntialias = true;
                    paint.StrokeWidth = 15;
                    paint.Style       = SKPaintStyle.Stroke;
                    canvas.DrawCircle(50, 50, 30, paint); //arguments are x position, y position, radius, and paint
                }

                using (SKImage image = surface.Snapshot())
                    using (SKData data = image.Encode(SKEncodedImageFormat.Png, 500))
                        using (MemoryStream mStream = new MemoryStream(data.ToArray()))
                        {
                            Bitmap bm = new Bitmap(mStream, false);
                            box.Image = bm;
                        }
            }
        }
예제 #4
0
        private byte[] GetBarcodeBytes(string text, BarcodeFormat format)
        {
            var       qrCodeWriter = new QRCodeWriter();
            BitMatrix bm           = qrCodeWriter.encode(text, format, 600, 600);
            int       squareLength = bm.Width;

            //HACK: we are manually creating each pixel? there must be an easier way
            SKBitmap bitmap = new SKBitmap(squareLength, squareLength);

            for (int row = 0; row < squareLength; row++)
            {
                for (int col = 0; col < squareLength; col++)
                {
                    if (bm[row, col])
                    {
                        bitmap.SetPixel(row, col, SKColors.Black);
                    }
                    else
                    {
                        bitmap.SetPixel(row, col, SKColors.White);
                    }
                }
            }

            SKData data = SKImage.FromBitmap(bitmap).Encode();

            return(data.ToArray());
        }
        private async void SaveAsImage(object sender, EventArgs e)
        {
            // First check for permissions (thanks Montemagno ;) )
            PermissionStatus status = await CrossPermissions.Current.CheckPermissionStatusAsync <StoragePermission>();

            if (status != PermissionStatus.Granted)
            {
                status = await CrossPermissions.Current.RequestPermissionAsync <StoragePermission>();
            }

            if (status == PermissionStatus.Granted)
            {
                SKData   data     = canvasImg.Encode();
                DateTime dt       = DateTime.Now;
                string   filename = String.Format("FingerPaint-{0:D4}{1:D2}{2:D2}-{3:D2}{4:D2}{5:D2}{6:D3}.png",
                                                  dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);

                IPhotoLibrary photoLibrary = DependencyService.Get <IPhotoLibrary>();
                bool          result       = await photoLibrary.SavePhotoAsync(data.ToArray(), "FingerPaint", filename);

                if (!result)
                {
                    await DisplayAlert("FingerPaint", "Artwork could not be saved. Sorry!", "OK");
                }
            }
            else
            {
                await DisplayAlert("Cannot save drawing", "Storage permission needed", "ok");
            }
        }
        private static byte[] 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);

            if (sourceBitmap.Height > maxHeight || sourceBitmap.Width > maxWidth)
            {
                if (sourceBitmap.Height > sourceBitmap.Width)
                {
                    width = (int)(sourceBitmap.Width / (sourceBitmap.Height / (double)maxHeight));
                }
                else
                {
                    height = (int)(sourceBitmap.Height / (sourceBitmap.Width / (double)maxWidth));
                }
            }

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

            return(data.ToArray());
        }
 private static byte[] GenerateImage()
 {
     using (SKBitmap bitmap = new SKBitmap(width: 200, height: 200))
     {
         using (SKCanvas canvas = new SKCanvas(bitmap))
         {
             var random = new Random();
             canvas.DrawColor(SKColor.FromHsl(random.Next(0, 360), 100, 50));
             using (var paint = new SKPaint()
             {
                 TextSize = 25.0f,
                 IsAntialias = true,
                 Color = new SKColor(0, 0, 0),
                 Style = SKPaintStyle.Fill,
                 TextAlign = SKTextAlign.Center
             })
             {
                 canvas.DrawText(DateTime.Now.ToString("T"), 100, 100, paint);
             }
             using (SKData data = SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Png, 100))
             {
                 return(data.ToArray());
             }
         }
     }
 }
        public void InsertImageFromByteArrayNetStandard2()
        {
            //ExStart
            //ExFor:DocumentBuilder.InsertImage(Byte[])
            //ExFor:DocumentBuilder.InsertImage(Byte[], Double, Double)
            //ExFor:DocumentBuilder.InsertImage(Byte[], RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType)
            //ExSummary:Shows different solutions of how to import an image into a document from a byte array (.NetStandard 2.0).
            Document        doc     = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            using (SKBitmap bitmap = SKBitmap.Decode(ImageDir + "Aspose.Words.gif"))
            {
                using (SKImage image = SKImage.FromBitmap(bitmap))
                {
                    using (SKData data = image.Encode()) // Encode the image (defaults to PNG)
                    {
                        byte[] imageByteArray = data.ToArray();

                        builder.Writeln("\nInserted image from byte array: ");
                        builder.InsertImage(imageByteArray);

                        builder.Writeln("\nInserted image from byte array with a custom size: ");
                        builder.InsertImage(imageByteArray, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

                        builder.Writeln("\nInserted image from byte array using relative positions: ");
                        builder.InsertImage(imageByteArray, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
                                            100, 200, 100, WrapType.Square);
                    }
                }
            }

            doc.Save(ArtifactsDir + "InsertImageFromByteArray.NetStandard2.docx");
            //ExEnd
        }
예제 #9
0
        /// <summary>
        /// This class takes care of the image processing. It implements a method for resizing images and another for
        /// adding watermarks
        ///
        /// It uses the library SkiaSharp
        ///
        /// The caller is agnostic of the library used, it passes and receives images as raw byte arrays. The class
        /// could be refactored to use a different library without affecting the rest of the code.
        ///
        /// Improvements could be made, like being able to specify the color or the location of the watermark
        /// </summary>
        /// <param name="image"></param>
        /// <param name="maxWidth"></param>
        /// <param name="maxHeight"></param>
        /// <param name="quality"></param>
        /// <returns></returns>
        public DrinkImage Resize(DrinkImage image, int maxWidth, int maxHeight,
                                 SKFilterQuality quality = SKFilterQuality.Medium)
        {
            using MemoryStream ms       = new MemoryStream(image.Bytes);
            using SKBitmap sourceBitmap = SKBitmap.Decode(ms);

            // Calculate height and width. We have to decide what to do when one of the parameters was not passed
            // and was defaulted to 0, or when the parameters passed have a different horizontal/vertical ratio
            // We want to create the smaller file that respects at least one of the 2 sizes provided and that has
            // the same horiz to vertical ratio as the image
            var horiz2vertRatio = sourceBitmap.Width / (double)sourceBitmap.Height;

            maxWidth  = maxWidth == 0 ? sourceBitmap.Width : maxWidth;
            maxHeight = maxHeight == 0 ? sourceBitmap.Height : maxHeight;
            var newHorizSize = (int)Math.Round(Math.Min(maxWidth, horiz2vertRatio * maxHeight));
            var newVertSize  = (int)Math.Round(Math.Min(maxHeight, maxWidth / horiz2vertRatio));


            using SKBitmap scaledBitmap = sourceBitmap.Resize(new SKImageInfo(newHorizSize, newVertSize), quality);
            using SKImage scaledImage   = SKImage.FromBitmap(scaledBitmap);
            using SKData data           = scaledImage.Encode();

            return(new DrinkImage
            {
                Bytes = data.ToArray(),
                HorizontalSize = newHorizSize,
                VerticalSize = newVertSize,
                Watermark = image.Watermark,
                ImageName = image.ImageName
            });
        }
예제 #10
0
        public static byte[] GenerateCodePng(string Text, int Width, int Height)
        {
            BarcodeWriterPixelData Writer = new BarcodeWriterPixelData()
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new QrCodeEncodingOptions()
                {
                    Width  = Width,
                    Height = Height
                }
            };

            PixelData QrCode = Writer.Write(Text);

            Width  = QrCode.Width;
            Height = QrCode.Height;

            int Size = Width * Height << 2;

            using (SKData Data = SKData.Create(Size))
            {
                Marshal.Copy(QrCode.Pixels, 0, Data.Data, Size);

                using (SKImage Result = SKImage.FromPixels(new SKImageInfo(Width, Height, SKColorType.Bgra8888), Data, Width << 2))
                {
                    using (SKData Encoded = Result.Encode(SKEncodedImageFormat.Png, 100))
                    {
                        return(Encoded.ToArray());
                    }
                }
            }
        }
예제 #11
0
        /// <summary>
        /// Save the image on the phone
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        //source: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/bitmaps/saving
        private async void saveImage(object sender, EventArgs args)
        {
            if (imgBitmap != null)
            {
                using (SKImage image = SKImage.FromBitmap(imgBitmap))
                {
                    try
                    {
                        SKData        data         = image.Encode();
                        IPhotoLibrary photoLibrary = DependencyService.Get <IPhotoLibrary>();
                        if (photoLibrary == null)
                        {
                            Console.WriteLine("SAVEIMAGE: photoLibrary null!");
                            return;
                        }

                        bool result = await photoLibrary.SavePhotoAsync(data.ToArray(), "Traumerei", Convert.ToString(Guid.NewGuid()));

                        if (!result)
                        {
                            Console.WriteLine("SAVEIMAGE: SavePhotoAsync return false");
                        }
                        else
                        {
                            Console.WriteLine("SAVEIMAGE: Success!");
                        }
                    }
                    catch (Exception ex)
                    {
                        string err = ex.InnerException.ToString();
                    }
                }
            }
        }
예제 #12
0
        public DrinkImage AddWatermark(DrinkImage imagen, string watermark)
        {
            using MemoryStream ms   = new MemoryStream(imagen.Bytes);
            using SKBitmap toBitmap = SKBitmap.Decode(ms);

            using SKCanvas canvas = new SKCanvas(toBitmap);

            using SKTypeface font = SKTypeface.FromFamilyName("Arial");
            using SKPaint brush   = new SKPaint
                  {
                      Typeface    = font,
                      TextSize    = toBitmap.Width * 3 / (watermark.Length * 2),
                      IsAntialias = true,
                      Color       = new SKColor(255, 255, 255, 255)
                  };
            canvas.DrawText(watermark, toBitmap.Width / 20, toBitmap.Height / 2, brush);

            canvas.Flush();

            using SKImage image = SKImage.FromBitmap(toBitmap);
            using SKData data   = image.Encode(SKEncodedImageFormat.Png, 90);

            return(new DrinkImage
            {
                Bytes = data.ToArray(),
                VerticalSize = imagen.VerticalSize,
                HorizontalSize = imagen.HorizontalSize,
                Watermark = watermark,
                ImageName = imagen.ImageName
            });
        }
예제 #13
0
        public void ValidDataProperties()
        {
            var data = new SKData(OddData);

            Assert.AreEqual(OddData.Length, data.Size);
            CollectionAssert.AreEqual(OddData, data.ToArray());
        }
        public async Task <IActionResult> MaintenanceConvertPicture([FromServices] IPictureService pictureService, [FromServices] MediaSettings mediaSettings, [FromServices] ILogger logger)
        {
            var model = new MaintenanceModel();

            model.ConvertedPictureModel.NumberOfConvertItems = 0;
            if (mediaSettings.StoreInDb)
            {
                var pictures = pictureService.GetPictures();
                foreach (var picture in pictures)
                {
                    if (!picture.MimeType.Contains("webp"))
                    {
                        try
                        {
                            using var image = SKBitmap.Decode(picture.PictureBinary);
                            SKData d = SKImage.FromBitmap(image).Encode(SKEncodedImageFormat.Webp, mediaSettings.DefaultImageQuality);
                            await pictureService.UpdatePicture(picture.Id, d.ToArray(), "image/webp", picture.SeoFilename, picture.AltAttribute, picture.TitleAttribute, true, false);

                            model.ConvertedPictureModel.NumberOfConvertItems += 1;
                        }
                        catch (Exception ex)
                        {
                            logger.Error($"Error on converting picture with id {picture.Id} to webp format", ex);
                        }
                    }
                }
            }
            return(View(model));
        }
예제 #15
0
        /// <summary>
        /// 将生成的字符串写入图像文件
        /// </summary>
        /// <param name="code">验证码字符串</param>
        /// <param name="length">生成位数(默认4位)</param>
        public static byte[] Create(out string code, int length = 4)
        {
            code = RandomCode(length);

            byte[] imageBytes;
            int    imageX = 85;
            int    imageY = 32;


            using (SKBitmap image = new SKBitmap(imageX, imageY, SKColorType.Bgra8888, SKAlphaType.Premul))
            {
                using (SKCanvas canvas = new SKCanvas(image))
                {
                    canvas.DrawColor(SKColors.Gray);
                    using (SKPaint drawStyle = CreatePaint())
                    {
                        canvas.DrawText(code, 10, imageY - 10, drawStyle);
                    }

                    using (SKImage img = SKImage.FromBitmap(image))
                    {
                        using (SKData p = img.Encode(SKEncodedImageFormat.Png, 100))
                        {
                            imageBytes = p.ToArray();
                        }
                    }
                }
            }

            return(imageBytes);
        }
예제 #16
0
        /// <summary>
        /// Resizes a given image with the given dimensions
        /// </summary>
        /// <param name="initialImage">the initial image</param>
        /// <param name="width">the new width</param>
        /// <param name="height">the new height</param>
        /// <returns>the resized version of the image</returns>
        public static byte[] ResizeImage(byte[] initialImage, int width, int height)
        {
            SKBitmap source = SKBitmap.Decode(initialImage);

            using SKBitmap scaledBitmap = source.Resize(new SKImageInfo(width, height), SKFilterQuality.Medium);
            using SKImage scaledImage   = SKImage.FromBitmap(scaledBitmap);
            using SKData data           = scaledImage.Encode();
            return(data.ToArray());
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static byte[] GetCode(out string code)
        {
            #region 反射SK支持的全部颜色
            //List<SKColor> colors = new List<SKColor>();
            //var skcolors = new SKColors();
            //var type = skcolors.GetType();
            //foreach (FieldInfo field in type.GetFields())
            //{
            //    colors.Add( (SKColor)field.GetValue(skcolors));
            //}
            #endregion

            //int maxcolorindex = colors.Count-1;
            byte[] imageBytes = null;
            code = GenerateRandomNumber(4, DateTime.Now.Second);
            var      zu  = code.ToList();
            SKBitmap bmp = new SKBitmap(80, 30);
            using (SKCanvas canvas = new SKCanvas(bmp))
            {
                //背景色
                canvas.DrawColor(SKColors.White);

                using (SKPaint sKPaint = new SKPaint())
                {
                    sKPaint.TextSize    = 16;                                                      //字体大小
                    sKPaint.IsAntialias = true;                                                    //开启抗锯齿
                    sKPaint.Typeface    = SKTypeface.FromFamilyName("微软雅黑", SKTypefaceStyle.Bold); //字体
                    SKRect size = new SKRect();
                    sKPaint.MeasureText(zu[0].ToString(), ref size);                               //计算文字宽度以及高度

                    float  temp   = (bmp.Width / 4 - size.Size.Width) / 2;
                    float  temp1  = bmp.Height - (bmp.Height - size.Size.Height) / 2;
                    Random random = new Random();

                    for (int i = 0; i < 4; i++)
                    {
                        sKPaint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));
                        canvas.DrawText(zu[i].ToString(), temp + 20 * i, temp1, sKPaint);//画文字
                    }
                    //干扰线
                    for (int i = 0; i < 5; 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())
                    {
                        imageBytes = p.ToArray();
                    }
                }
                return(imageBytes);
            }
        }
예제 #18
0
        public IActionResult ValidateCode()
        {
            #region 反射SK支持的全部颜色
            //List<SKColor> colors = new List<SKColor>();
            //var skcolors = new SKColors();
            //var type = skcolors.GetType();
            //foreach (FieldInfo field in type.GetFields())
            //{
            //    colors.Add( (SKColor)field.GetValue(skcolors));
            //}
            #endregion

            //int maxcolorindex = colors.Count-1;
            string   text = Bucket.Utility.Helpers.Randoms.CreateRandomValue(5, false);
            var      zu   = text.ToList();
            SKBitmap bmp  = new SKBitmap(100, 50);
            using (SKCanvas canvas = new SKCanvas(bmp))
            {
                //背景色
                canvas.DrawColor(SKColors.White);
                using (SKPaint sKPaint = new SKPaint())
                {
                    sKPaint.TextSize    = 24;                                                       //字体大小
                    sKPaint.IsAntialias = true;                                                     //开启抗锯齿
                    sKPaint.Typeface    = SKTypeface.FromFamilyName("Arial", SKTypefaceStyle.Bold); //字体

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

                    float  temp   = (bmp.Width / 4 - size.Size.Width) / 2;
                    float  temp1  = bmp.Height - (bmp.Height - size.Size.Height) / 2;
                    Random random = new Random();

                    for (int i = 0; i < zu.Count; i++)
                    {
                        sKPaint.Color     = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));
                        sKPaint.TextSkewX = (float)random.Next(0, 2);
                        canvas.DrawText(zu[i].ToString(), temp + 20 * i, temp1 + random.Next(-5, 5), sKPaint);//画文字
                    }
                    //干扰线
                    for (int i = 0; i < 5; 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(File(p.ToArray(), "image/Png"));
                    }
                }
            }
        }
예제 #19
0
        private void ReturnMomentaryAsWebp(HttpRequest Request, HttpResponse Response)
        {
            SKImage Gauge = this.GenerateGauge(Request.Header);
            SKData  Data  = Gauge.Encode(SKEncodedImageFormat.Webp, 90);

            byte[] Binary = Data.ToArray();

            Response.ContentType = "image/webp";
            Response.Write(Binary);
        }
예제 #20
0
        private static async Task <bool> SaveSKBitmapAsync(SKBitmap sKBitmap, string fullPath)
        {
            //Save
            using SKImage image = SKImage.FromBitmap(sKBitmap);

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

            fullPath = Path.ChangeExtension(fullPath, ".png");

            return(await FileUtil.TrySaveFileAsync(data.ToArray(), fullPath).ConfigureAwait(false));
        }
예제 #21
0
        /// <summary>
        /// Event thrown when touching the "Valider" button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        async Task OnValidateButtonClickedAsync(object sender, EventArgs e)
        {
            if (entryName.Text == null || entryName.Text.Equals(""))
            {
                await DisplayAlert("Erreur", "Le nom du signataire ne doit pas être vide", "OK");

                return;
            }

            SKImageInfo info    = new SKImageInfo(widthExport, heightExport);
            var         surface = SKSurface.Create(info);
            var         canvas  = surface.Canvas;

            foreach (SKPath path in completedPathsResize)
            {
                canvas.DrawPath(path, paint);
            }

            foreach (SKPath path in inProgressPathsResize.Values)
            {
                canvas.DrawPath(path, paint);
            }


            SKImage snap = surface.Snapshot();

            data = snap.Encode();

            Eval.IsSigned             = true;
            CurrentCandidate.IsSigned = true;


            Eval.Signatures.Add(new Signature(entryName.Text, data.ToArray()));
            bool answer = await DisplayAlert("Signature", "Voulez-vous effectuer une autre signature ?", "Oui", "Non");

            if (!answer)
            {
                await Navigation.PopAsync();
            }
            else
            {
                data = null;
                if (canvasSaved != null)
                {
                    canvasSaved = null;
                }
                canvasView.InvalidateSurface();
                completedPaths.Clear();
                inProgressPaths.Clear();
                completedPathsResize.Clear();
                inProgressPathsResize.Clear();
                entryName.Text = "";
            }
        }
예제 #22
0
        } // End Function MeasureText

        // https://gist.github.com/zester/1177738
        // https://forums.xamarin.com/discussion/75958/using-skiasharp-how-to-save-a-skbitmap
        private void DrawWithoutSurface()
        {
            // SKImageInfo nfo = new SKImageInfo();
            // SKBitmap bmp = new SKBitmap(300, 300, SKColorType.Rgba8888, SKAlphaType.Opaque);
            SKBitmap bmp = new SKBitmap(300, 300, SKColorType.Bgra8888, SKAlphaType.Premul);

            using (SKCanvas canvas = new SKCanvas(bmp))
            {
                canvas.DrawColor(SKColors.White); // Clear

                using (SKPaint paint = new SKPaint())
                {
                    // paint.ImageFilter = SKImageFilter.CreateBlur(5, 5); // Dispose !
                    paint.IsAntialias = true;
                    // paint.Color = new SKColor(0xff, 0x00, 0xff);
                    paint.Color = new SKColor(0x2c, 0x3e, 0x50);

                    paint.StrokeCap = SKStrokeCap.Round;

                    paint.Typeface = SkiaSharp.SKTypeface.FromFamilyName("Linux Libertine G", SKTypefaceStyle.Normal);
                    paint.Typeface = SkiaSharp.SKTypeface.FromFamilyName("Segoe Script", SKTypefaceStyle.Italic);
                    paint.TextSize = 10;

                    canvas.DrawText("This is a test", 20, 20, paint);


                    paint.Typeface = SkiaSharp.SKTypeface.FromFamilyName("fadfasdjf", SKTypefaceStyle.Normal);
                    canvas.DrawText("This is a test with an unknown font", 20, 60, paint);
                } // End Using paint
            }     // End Using canvas

            SKData p = SKImage.FromBitmap(bmp).Encode(SKImageEncodeFormat.Png, 100);

            // p.SaveTo(strm);
            System.IO.File.WriteAllBytes(MapProjectPath("~NoSurfaceTest.png"), p.ToArray());

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(p.ToArray()))
            {
                this.pictureBox1.Image = System.Drawing.Image.FromStream(ms);
            } // End Using ms
        }     // End Sub DrawWithoutSurface
예제 #23
0
 private async void Button_Clicked_2(object sender, EventArgs e)
 {
     if (pngImage != null)
     {
         byte[] data = pngImage.ToArray();
         await mediaHelper.SaveImage(data, "L", "emy.jpg");
     }
     else
     {
         await DisplayAlert("Alert", "Image no saved.", "Ok");
     }
 }
예제 #24
0
        private void Save(SKImage Image, string FileName)
        {
            if (!Directory.Exists("Graphs"))
            {
                Directory.CreateDirectory("Graphs");
            }

            using (SKData Data = Image.Encode(SKEncodedImageFormat.Png, 100))
            {
                File.WriteAllBytes(Path.Combine("Graphs", FileName), Data.ToArray());
            }
        }
예제 #25
0
        public byte[] Resize(
            MemoryStream fileContents,
            int maxWidth,
            int maxHeight)
        {
            using SKBitmap sourceBitmap = SKBitmap.Decode(fileContents);

            using SKBitmap scaledBitmap = sourceBitmap.Resize(new SKImageInfo(maxWidth, maxHeight), SKFilterQuality.Medium);
            using SKImage scaledImage   = SKImage.FromBitmap(scaledBitmap);
            using SKData data           = scaledImage.Encode();

            return(data.ToArray());
        }
예제 #26
0
        private async Task <byte[]> CreateMapImageAsync(
            int width,
            int height,
            Models.Bounds boundingBox,
            string mediaType,
            bool isTransparent,
            uint backgroundColor,
            IList <string> layerNames)
        {
            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(backgroundColor));

            foreach (var layerName in layerNames)
            {
                if (this.tileSourceFabric.Contains(layerName))
                {
                    await WmsHelper.DrawLayerAsync( // TODO: ? pass required format to avoid conversions
                        this.tileSourceFabric.Get(layerName),
                        width,
                        height,
                        boundingBox,
                        canvas,
                        isTransparent,
                        backgroundColor);
                }
            }

            using SKImage image = surface.Snapshot();

            if (String.Compare(mediaType, MediaTypeNames.Image.Tiff, StringComparison.OrdinalIgnoreCase) == 0)
            {
                using var bitmap = SKBitmap.FromImage(image);
                // TODO: improve performance of pixels processing, maybe using unsafe/pointers
                var pixels = bitmap.Pixels.SelectMany(p => new byte[] { p.Red, p.Green, p.Blue, p.Alpha }).ToArray();
                var tiff   = ImageHelper.CreateTiffImage(pixels, image.Width, image.Height);
                return(tiff);
            }
            else
            {
                var imageFormat = U.ImageHelper.SKEncodedImageFormatFromMediaType(mediaType);
                using SKData data = image.Encode(imageFormat, 90); // TODO: ? quality parameter
                return(data.ToArray());
            }
        }
        public void initialize(string argument)
        {
            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;

                delete_data();
            }
            catch (System.Exception error)
            {
                Console.WriteLine("" + error);
            }
        }
예제 #28
0
        /// <summary>
        /// Exports graph specifics to XML.
        /// </summary>
        /// <param name="Output">XML output.</param>
        public override void ExportGraph(XmlWriter Output)
        {
            Output.WriteStartElement("GraphBitmap");
            Output.WriteAttributeString("width", this.width.ToString());
            Output.WriteAttributeString("height", this.height.ToString());

            using (SKData Data = this.bitmap.Encode(SKEncodedImageFormat.Png, 100))
            {
                byte[] Bin = Data.ToArray();
                Output.WriteElementString("Png", Convert.ToBase64String(Bin));
            }

            Output.WriteEndElement();
        }
        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());
        }
예제 #30
0
        public void Render()
        {
            var regionNamesRenderTask         = new RegionNamesMapRenderTask();
            var solarSystemsMapRenderTask     = new SolarSystemsMapRenderTask();
            var solarSystemJumpsMapRenderTask = new SolarSystemJumpsMapRenderTask();
            var voronoiSovMapRenderTask       = new VoronoiSovMapRenderTask();

            var imageInfo = new SKImageInfo(MapConstants.HORIZONTAL_SIZE, MapConstants.VERTICAL_SIZE, SKImageInfo.PlatformColorType, SKAlphaType.Premul);

            using (var surface = SKSurface.Create(imageInfo)) {
                SKCanvas myCanvas = surface.Canvas;
                myCanvas.Clear(SKColors.Black);

                using (var paint = new SKPaint())
                {
                    // paint.Style = SKPaintStyle.StrokeAndFill;
                    // paint.Color = new SKColor(0xB0, 0xB0, 0xFF);
                    // paint.IsAntialias = true;

                    voronoiSovMapRenderTask.Render(myCanvas, _dataContext);
                    solarSystemJumpsMapRenderTask.Render(myCanvas, _dataContext);
                    solarSystemsMapRenderTask.Render(myCanvas, _dataContext);
                    regionNamesRenderTask.Render(myCanvas, _dataContext);



                    using (SKImage image = surface.Snapshot())
                        using (SKData data = image.Encode(SKEncodedImageFormat.Png, 100))
                            using (var fileStream = File.Create("sovMap.png"))
                            {
                                fileStream.Write(data.ToArray(), 0, data.ToArray().Length);
                            }
                }

                // Your drawing code goes here.
            }
        }