コード例 #1
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="peopleViewModel">PeopleViewModel for adding the person.</param>
        public NewPersonPage(PeopleViewModel peopleViewModel)
        {
            InitializeComponent();

            string   resourceID = "FaceRecognition.placeholder_image.png";
            Assembly assembly   = GetType().GetTypeInfo().Assembly;

            using (Stream stream = assembly.GetManifestResourceStream(resourceID))
            {
                bitmap = SKBitmap.Decode(stream);
            }

            var item = new Person
            {
                name = "Name"
            };

            viewModel       = new ImageViewModel(item);
            BindingContext  = viewModel;
            PeopleViewModel = peopleViewModel;
        }
コード例 #2
0
        public Image(string path)
        {
            using (var input = File.OpenRead(path))
                using (var inputStream = new SKManagedStream(input))
                    using (var bitmap = SKBitmap.Decode(inputStream))
                    {
                        Width  = bitmap.Width;
                        Height = bitmap.Height;
                        _data  = new byte[Width, Height];

                        for (int x = 0; x < Width; x++)
                        {
                            for (int y = 0; y < Height; y++)
                            {
                                var value = bitmap.GetPixel(x, y).Red;
                                _data[x, y] = value;
                            }
                        }
                    }
            ComputeHash();
        }
コード例 #3
0
 /// <summary>
 /// Optimizes the specified source image and returns the binary data of the output image.
 /// </summary>
 public byte[] Optimize(byte[] sourceData, bool toJpeg = true)
 {
     try
     {
         using (var source = SKBitmap.Decode(sourceData))
         {
             using (var resultBitmap = Optimize(source))
             {
                 using (SKImage image = SKImage.FromBitmap(resultBitmap))
                 {
                     return(image.Encode(toJpeg ? SKEncodedImageFormat.Jpeg : SKEncodedImageFormat.Png, Quality).ToArray());
                 }
             }
         }
     }
     catch
     {
         // No Logging Needed
         return(sourceData);
     }
 }
コード例 #4
0
        public void TestBitmapDecodeDrawsCorrectly()
        {
            var path = Path.Combine(PathToImages, "color-wheel.png");

            using (var bitmap = SKBitmap.Decode(path))
                using (var surface = SKSurface.Create(new SKImageInfo(200, 200)))
                {
                    var canvas = surface.Canvas;
                    canvas.Clear(SKColors.White);
                    canvas.DrawBitmap(bitmap, 0, 0);

                    using (var img = surface.Snapshot())
                        using (var bmp = SKBitmap.FromImage(img))
                        {
                            Assert.Equal(new SKColor(2, 255, 42), bmp.GetPixel(20, 20));
                            Assert.Equal(new SKColor(1, 83, 255), bmp.GetPixel(108, 20));
                            Assert.Equal(new SKColor(255, 166, 1), bmp.GetPixel(20, 108));
                            Assert.Equal(new SKColor(255, 1, 214), bmp.GetPixel(108, 108));
                        }
                }
        }
コード例 #5
0
            public void WithBaseSizeResizes()
            {
                var info = new ResizeImageInfo();

                info.Filename = "images/camera_color.png";
                info.BaseSize = new Size(512, 512);
                var tools   = new SkiaSharpBitmapTools(info, Logger);
                var dpiPath = new DpiPath("", 1);

                tools.Resize(dpiPath, DestinationFilename);

                using var resultImage = SKBitmap.Decode(DestinationFilename);
                Assert.Equal(512, resultImage.Width);
                Assert.Equal(512, resultImage.Height);

                using var pixmap = resultImage.PeekPixels();
                Assert.Equal(SKColors.Empty, pixmap.GetPixelColor(10, 10));
                Assert.Equal(SKColors.Red, pixmap.GetPixelColor(74, 274));
                Assert.Equal(SKColors.Lime, pixmap.GetPixelColor(162, 274));
                Assert.Equal(SKColors.Blue, pixmap.GetPixelColor(250, 274));
            }
コード例 #6
0
            public void WithBaseSizeAndScaleResizes()
            {
                var info = new SharedImageInfo();

                info.Filename = "images/camera_color.svg";
                info.BaseSize = new Size(512, 512);
                var tools   = new SkiaSharpSvgTools(info, Logger);
                var dpiPath = new DpiPath("", 0.5m);

                tools.Resize(dpiPath, DestinationFilename);

                using var resultImage = SKBitmap.Decode(DestinationFilename);
                Assert.Equal(256, resultImage.Width);
                Assert.Equal(256, resultImage.Height);

                using var pixmap = resultImage.PeekPixels();
                Assert.Equal(SKColors.Empty, pixmap.GetPixelColor(10, 10));
                Assert.Equal(SKColors.Red, pixmap.GetPixelColor(37, 137));
                Assert.Equal(SKColors.Lime, pixmap.GetPixelColor(81, 137));
                Assert.Equal(SKColors.Blue, pixmap.GetPixelColor(125, 137));
            }
コード例 #7
0
        /// <summary>
        ///     Draws the Controller Bitmap onto the Canvas for Controller
        /// </summary>
        /// <param name="e"></param>
        void PaintController(SKPaintSurfaceEventArgs e)
        {
            var controllerRect  = new SKRect(0, 0, e.Info.Rect.Right, (e.Info.Rect.Right / 2.56f));
            var controllerImage = SKBitmap.Decode(_resourceReader.GetResource(ResourceControllerImage));

            //Determine the ratios difference between the original image and the resized image
            var xRatio = ((float)controllerRect.Width / controllerImage.Width);
            var yRatio = ((float)controllerRect.Height / controllerImage.Height);

            _controllerLeftRect   = new SKRect(50 * xRatio, 127 * yRatio, 95 * xRatio, 180 * yRatio);
            _controllerRightRect  = new SKRect(150 * xRatio, 127 * yRatio, 190 * xRatio, 180 * yRatio);
            _controllerUpRect     = new SKRect(95 * xRatio, 75 * yRatio, 155 * xRatio, 120 * yRatio);
            _controllerDownRect   = new SKRect(95 * xRatio, 180 * yRatio, 150 * xRatio, 225 * yRatio);
            _controllerStartRect  = new SKRect(350 * xRatio, 175 * yRatio, 400 * xRatio, 205 * yRatio);
            _controllerSelectRect = new SKRect(260 * xRatio, 175 * yRatio, 310 * xRatio, 205 * yRatio);
            _controllerARect      = new SKRect(570 * xRatio, 160 * yRatio, 635 * xRatio, 225 * yRatio);
            _controllerBRect      = new SKRect(475 * xRatio, 160 * yRatio, 540 * xRatio, 225 * yRatio);

            e.Surface.Canvas.Clear(SKColors.Black);
            e.Surface.Canvas.DrawBitmap(controllerImage, controllerRect);
        }
コード例 #8
0
            public void ColorizedWithAlphaWithColorsReplacesColors()
            {
                var info = new SharedImageInfo();

                info.Filename  = "images/camera_color.svg";
                info.TintColor = Color.FromArgb(127, Color.Red);
                var tools   = new SkiaSharpSvgTools(info, Logger);
                var dpiPath = new DpiPath("", 1);

                tools.Resize(dpiPath, DestinationFilename);

                using var resultImage = SKBitmap.Decode(DestinationFilename);
                Assert.Equal(256, resultImage.Width);
                Assert.Equal(256, resultImage.Height);

                using var pixmap = resultImage.PeekPixels();
                Assert.Equal(SKColors.Empty, pixmap.GetPixelColor(10, 10));
                Assert.Equal(SKColors.Red.WithAlpha(127), pixmap.GetPixelColor(37, 137));
                Assert.Equal(SKColors.Red.WithAlpha(127), pixmap.GetPixelColor(81, 137));
                Assert.Equal(SKColors.Red.WithAlpha(127), pixmap.GetPixelColor(125, 137));
            }
コード例 #9
0
        public void DecodingWithBitmapCreatesCorrectImage()
        {
            var info = new SKImageInfo(120, 120);
            var path = Path.Combine(PathToImages, "vimeo_icon_dark.png");

            using (var bmp = new SKBitmap(info))
                using (var canvas = new SKCanvas(bmp))
                {
                    canvas.Clear(SKColors.Crimson);

                    using (var bitmap = SKBitmap.Decode(path))
                        using (var image = SKImage.FromBitmap(bitmap))
                        {
                            canvas.DrawImage(image, 0, 0);
                        }

                    Assert.Equal(SKColors.Crimson, bmp.GetPixel(3, 3));
                    Assert.Equal(SKColors.Crimson, bmp.GetPixel(70, 50));
                    Assert.Equal(new SKColor(23, 35, 34), bmp.GetPixel(40, 40));
                }
        }
コード例 #10
0
        private void PlaceWatermark(string filePath)
        {
            SKImage  finalImage;
            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, 1000, 1000));

                SKBitmap stamp = SKBitmap.Decode("storage/emulated/0/Android/data/com.companyname.Forms/files/Pictures/Sample/test_1.jpg");

                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 temp = new Image
                    {
                        Source = ImageSource.FromFile("storage/emulated/0/Android/data/com.companyname.Forms/files/Pictures/Sample/final.jpg")
                    };
                    image.Source = ImageSource.FromFile("storage/emulated/0/Android/data/com.companyname.Forms/files/Pictures/Sample/final.jpg");
                }
        }
コード例 #11
0
        private void SKElement_OnPaintSurface(object sender, SKPaintSurfaceEventArgs e)
        {
            SKCanvas canvas = e.Surface.Canvas;

            canvas.Clear();

            //TODO: bad check, should handle exception
            if (SelectedFile?.Exists != true)
            {
                return;
            }

            var element = (SKElement)sender;

            //TODO: Horribly inefficient
            using (Stream imageStream = SelectedFile.OpenRead())
                using (SKBitmap bitmap = SKBitmap.Decode(imageStream))
                    using (SKPaint paint = new SKPaint())
                        using (SKImageFilter filter = GetImageFilters().FirstOrDefault())
                        {
                            paint.ImageFilter = filter;
                            float x = 0, y = 0;
                            if (Offset != null)
                            {
                                x = (float)Offset.Value.X;
                                y = (float)Offset.Value.Y;
                            }

                            var source = new SKRect(x, y, x + (float)element.ActualWidth, y + (float)element.ActualHeight);
                            canvas.DrawBitmap(bitmap, source, new SKRect(0, 0, (float)element.ActualWidth, (float)element.ActualHeight), paint);
                        }

            IEnumerable <SKImageFilter> GetImageFilters()
            {
                if (int.TryParse(Blur.Text, out int blurValue) && blurValue > 0)
                {
                    yield return(SKImageFilter.CreateBlur(blurValue, blurValue));
                }
            }
        }
コード例 #12
0
        private void Canvas_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
        {
            SKImageInfo info    = e.Info;
            SKSurface   surface = e.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();
            if (character != null)
            {
                Assembly assembly = GetType().GetTypeInfo().Assembly;
                string[] images   = new string[5];
                images[0] = character.Image;
                images[1] = "Betrayal.Resources.overlays.speed_" + currentSpeed + ".png";
                images[2] = "Betrayal.Resources.overlays.might_" + currentMight + ".png";
                images[3] = "Betrayal.Resources.overlays.sanity_" + currentSanity + ".png";
                images[4] = "Betrayal.Resources.overlays.knowledge_" + currentKnowledge + ".png";

                foreach (string s in images)
                {
                    if (!string.IsNullOrWhiteSpace(s))
                    {
                        using (Stream stream = assembly.GetManifestResourceStream(s))
                        {
                            SKBitmap resourceBitmap = SKBitmap.Decode(stream);
                            SKRectI  pictureFrame   = info.Rect;
                            SKSizeI  imageSize      = resourceBitmap.Info.Size;
                            SKRectI  dest           = pictureFrame.AspectFit(imageSize); // fit the size inside the rect

                            // draw the image
                            SKPaint paint = new SKPaint
                            {
                                FilterQuality = SKFilterQuality.High // high quality scaling
                            };
                            canvas.DrawBitmap(resourceBitmap, dest, paint);
                        }
                    }
                }
                EnableControls();
            }
        }
コード例 #13
0
        /// <summary>
        /// Take a path provided by a user, draw it as a maptile. Potentially useful for exercise trackers. Resulting file must not be saved to the server as that would be user tracking.
        /// </summary>
        /// <param name="pointListAsString">a string of points separate by , and | </param>
        /// <returns>the png file with the path drawn over the mapdata in the area.</returns>
        public byte[] DrawUserPath(string pointListAsString)
        {
            //String is formatted as Lat,Lon~Lat,Lon~ repeating. Characters chosen to not be percent-encoded if submitted as part of the URL.
            //first, convert this to a list of latlon points
            string[]          pointToConvert = pointListAsString.Split("|");
            List <Coordinate> coords         = pointToConvert.Select(p => new Coordinate(double.Parse(p.Split(',')[0]), double.Parse(p.Split(',')[1]))).ToList();

            var     mapBuffer = resolutionCell8 / 2; //Leave some area around the edges of where they went.
            GeoArea mapToDraw = new GeoArea(coords.Min(c => c.Y) - mapBuffer, coords.Min(c => c.X) - mapBuffer, coords.Max(c => c.Y) + mapBuffer, coords.Max(c => c.X) + mapBuffer);

            ImageStats info = new ImageStats(mapToDraw, 1024, 1024);

            LineString line         = new LineString(coords.ToArray());
            var        drawableLine = PolygonToSKPoints(line, mapToDraw, info.degreesPerPixelX, info.degreesPerPixelY);

            //Now, draw that path on the map.
            var places    = GetPlaces(mapToDraw); //, null, false, false, degreesPerPixelX * 4 ///TODO: restore item filtering
            var baseImage = DrawAreaAtSize(info, places);

            SKBitmap sKBitmap = SKBitmap.Decode(baseImage);
            SKCanvas canvas   = new SKCanvas(sKBitmap);
            SKPaint  paint    = new SKPaint();

            paint.Style       = SKPaintStyle.Stroke;
            paint.StrokeWidth = 4;                    //Larger than normal lines at any zoom level.
            paint.Color       = new SKColor(0, 0, 0); //Pure black, for maximum visibility.
            for (var x = 0; x < drawableLine.Length - 1; x++)
            {
                canvas.DrawLine(drawableLine[x], drawableLine[x + 1], paint);
            }

            var ms   = new MemoryStream();
            var skms = new SKManagedWStream(ms);

            sKBitmap.Encode(skms, SKEncodedImageFormat.Png, 100);
            var results = ms.ToArray();

            skms.Dispose(); ms.Close(); ms.Dispose();
            return(results);
        }
コード例 #14
0
        static void SkiaBitmapLoadResizeSave(string path, int size, string outputDirectory)
        {
            using (var input = File.OpenRead(path))
            {
                using (var inputStream = new SKManagedStream(input))
                {
                    using (var original = SKBitmap.Decode(inputStream))
                    {
                        int width, height;
                        if (original.Width > original.Height)
                        {
                            width  = size;
                            height = original.Height * size / original.Width;
                        }
                        else
                        {
                            width  = original.Width * size / original.Height;
                            height = size;
                        }

                        using (var resized = original.Resize(new SKImageInfo(width, height), SKBitmapResizeMethod.Lanczos3))
                        {
                            if (resized == null)
                            {
                                return;
                            }

                            using (var image = SKImage.FromBitmap(resized))
                            {
                                using (var output = File.OpenWrite(OutputPath(path, outputDirectory, SkiaSharpBitmap)))
                                {
                                    image.Encode(SKEncodedImageFormat.Jpeg, Quality)
                                    .SaveTo(output);
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #15
0
ファイル: SkiaEncoder.cs プロジェクト: tnt-wolve/Emby
        internal static SKBitmap Decode(string path, bool forceCleanBitmap, out SKCodecOrigin origin)
        {
            var requiresTransparencyHack = TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty);

            if (requiresTransparencyHack || forceCleanBitmap)
            {
                using (var stream = new SKFileStream(path))
                {
                    var codec = SKCodec.Create(stream);

                    // create the bitmap
                    var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
                    // decode
                    codec.GetPixels(bitmap.Info, bitmap.GetPixels());

                    origin = codec.Origin;

                    return(bitmap);
                }
            }

            var resultBitmap = SKBitmap.Decode(path);

            if (resultBitmap == null)
            {
                return(Decode(path, true, out origin));
            }

            // If we have to resize these they often end up distorted
            if (resultBitmap.ColorType == SKColorType.Gray8)
            {
                using (resultBitmap)
                {
                    return(Decode(path, true, out origin));
                }
            }

            origin = SKCodecOrigin.TopLeft;
            return(resultBitmap);
        }
コード例 #16
0
        public static SKBitmap ToBitmap(int shopType)
        {
            string fileName = "";

            switch (shopType)
            {
            case 0:
                fileName = "shoppingcart.png";
                break;

            case 1:
                fileName = "car.png";
                break;

            case 2:
                fileName = "fork.png";
                break;

            case 3:
                fileName = "joystick.png";
                break;

            case 4:
                fileName = "house.png";
                break;

            case 5:
                fileName = "tag.png";
                break;

            default:
                fileName = "tag.png";
                break;
            }
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                var info = new SKImageInfo(20, 20);
                return(SKBitmap.Decode(fs, info));
            }
        }
コード例 #17
0
        protected void CheckSimpleRenderTileResponse(SKBitmap bitmap, string fileName = "", string compareToFile = "")
        {
            // Convert the response into a bitmap
            bitmap.Should().NotBeNull();

            if (!string.IsNullOrEmpty(fileName))
            {
                using var image  = SKImage.FromBitmap(bitmap);
                using var data   = image.Encode(SKEncodedImageFormat.Png, 100);
                using var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
                data.SaveTo(stream);
            }
            else
            {
                // If the comparison file does not exist then create it to provide a base comparison moving forward.
                if (!string.IsNullOrEmpty(compareToFile) && !File.Exists(compareToFile))
                {
                    using var image  = SKImage.FromBitmap(bitmap);
                    using var data   = image.Encode(SKEncodedImageFormat.Png, 100);
                    using var stream = new FileStream(compareToFile, FileMode.Create, FileAccess.Write, FileShare.None);
                    data.SaveTo(stream);
                }
            }

            if (!string.IsNullOrEmpty(compareToFile))
            {
                var goodBmp = SKBitmap.Decode(compareToFile);

                goodBmp.Height.Should().Be(bitmap.Height);
                goodBmp.Width.Should().Be(bitmap.Width);

                for (var i = 0; i <= bitmap.Width - 1; i++)
                {
                    for (var j = 0; j < bitmap.Height - 1; j++)
                    {
                        goodBmp.GetPixel(i, j).Should().Be(bitmap.GetPixel(i, j));
                    }
                }
            }
        }
コード例 #18
0
        private SKBitmap CreateQrBitmap(string text, int width, int height)
        {
            var writer = new BarcodeWriterPixelData
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new QrCodeEncodingOptions
                {
                    Width  = width,
                    Height = height
                }
            };

            var data = writer.Write(text);

            using (var bitmap = new Bitmap(data.Width, data.Height, PixelFormat.Format32bppRgb))
                using (var ms = new MemoryStream())
                {
                    var bitmapData = bitmap.LockBits(
                        new Rectangle(0, 0, data.Width, data.Height),
                        ImageLockMode.WriteOnly,
                        PixelFormat.Format32bppRgb);
                    try
                    {
                        Marshal.Copy(data.Pixels, 0, bitmapData.Scan0, data.Pixels.Length);
                    }
                    finally
                    {
                        bitmap.UnlockBits(bitmapData);
                    }

                    bitmap.Save(ms, ImageFormat.Bmp);

                    ms.Seek(0, SeekOrigin.Begin);

                    using (var stream = new SKManagedStream(ms))
                    {
                        return(SKBitmap.Decode(stream));
                    }
                }
        }
コード例 #19
0
        public override void Initiate(ILaunchpad launchpad)
        {
            this.launchpad = launchpad as LaunchpadMk2;
            try
            {
                using (var fileStream = File.OpenText(_filePath))
                {
                    var contents = fileStream.ReadToEnd();
                    piskelFile = new PiskelFile(contents);
                }

                var pngData = piskelFile.Layers.First().Chunks.First().Data;
                bitmap = SKBitmap.Decode(pngData);

                var totalFrames = piskelFile.Layers.First().FrameCount;
                var frameWidth  = bitmap.Width / totalFrames;

                for (var frameIndex = 0; frameIndex < totalFrames; frameIndex++)
                {
                    var frame   = new Color[frameWidth, bitmap.Height];
                    var xOffset = frameIndex * frameWidth;
                    for (var y = 0; y < bitmap.Height; y++)
                    {
                        for (var x = 0; x < frameWidth; x++)
                        {
                            var pixel = bitmap.Pixels[bitmap.Width * y + (x + xOffset)];
                            frame[x, y] = Color.FromArgb(pixel.Alpha, pixel.Red, pixel.Green, pixel.Blue);
                        }
                    }
                    frames.Add(frame);
                }


                isInitiated = true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: wuanunet/DotNetCoreCourse
        static void Main(string[] args)
        {
            var resizeFactor = 0.5f;
            var bitmap       = SKBitmap.Decode("input.png");
            var toBitmap     = new SKBitmap((int)Math.Round(bitmap.Width * resizeFactor), (int)Math.Round(bitmap.Height * resizeFactor), bitmap.ColorType, bitmap.AlphaType);

            var canvas = new SKCanvas(toBitmap);

            // Draw a bitmap rescaled
            canvas.SetMatrix(SKMatrix.MakeScale(resizeFactor, resizeFactor));
            canvas.DrawBitmap(bitmap, 0, 0);
            canvas.ResetMatrix();

            var font  = SKTypeface.FromFamilyName("Arial");
            var brush = new SKPaint
            {
                Typeface    = font,
                TextSize    = 40.0f,
                IsAntialias = true,
                Color       = new SKColor(255, 255, 255, 255)
            };

            canvas.DrawText("Resized!", 0, bitmap.Height * resizeFactor / 2.0f, brush);

            canvas.Flush();

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

            using (var stream = new FileStream("output.png", FileMode.Create, FileAccess.Write))
                data.SaveTo(stream);

            data.Dispose();
            image.Dispose();
            canvas.Dispose();
            brush.Dispose();
            font.Dispose();
            toBitmap.Dispose();
            bitmap.Dispose();
        }
コード例 #21
0
        private Result GetImagePart(Mnemonic expression, IRuntime runtime)
        {
            if (
                runtime.GetVariable("arrayOfBinaryData").Get(runtime) is String arrayImage &&
                runtime.GetVariable("left").Get(runtime) is Number a &&
                runtime.GetVariable("top").Get(runtime) is Number b &&
                runtime.GetVariable("right").Get(runtime) is Number c &&
                runtime.GetVariable("bottom").Get(runtime) is Number d
                )
            {
                var binaryData =
                    Convert.FromBase64String(arrayImage.Value);

                //arrayImage
                //.Select(e => e as Number)
                //.Select(n => n.ValueAsByte)
                //.ToArray();
                var resourceBitmap = SKBitmap.Decode(binaryData);

                var bmp = new SKBitmap();
                resourceBitmap.ExtractSubset(bmp,
                                             new SKRectI(a.ValueAsInt, b.ValueAsInt, c.ValueAsInt, d.ValueAsInt));

                SKDynamicMemoryWStream ms = new SKDynamicMemoryWStream();
                var data = bmp.Encode(SKEncodedImageFormat.Png, 100);

                var subimage = Convert.ToBase64String(data.ToArray());
                //LoplaList loplaList = new LoplaList();

                //foreach(var dbyte in data.ToArray())
                //{
                //    loplaList.Add(new Number(dbyte));
                //}

                //return new Result(loplaList);
                return(new Result(new String(subimage)));
            }

            return(new Result());
        }
コード例 #22
0
        public async Task <IActionResult> MaintenanceConvertPicture([FromServices] IPictureService pictureService, [FromServices] MediaSettings mediaSettings)
        {
            var model = new MaintenanceModel();

            model.ConvertedPictureModel.NumberOfConvertItems = 0;
            if (pictureService.StoreInDb)
            {
                var pictures = pictureService.GetPictures();
                foreach (var picture in pictures)
                {
                    if (!picture.MimeType.Contains("webp"))
                    {
                        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;
                    }
                }
            }
            return(View(model));
        }
コード例 #23
0
        /// <summary>
        /// Get files in the passed directory
        /// </summary>
        /// <param name="directoryPath">Path to the files directory</param>
        /// <param name="type">Type of the files</param>
        /// <returns>A task that represents the completion of the operation</returns>
        protected virtual async Task GetFilesAsync(string directoryPath, string type)
        {
            directoryPath = GetVirtualPath(directoryPath);
            var files = GetFiles(GetFullPath(directoryPath), type);

            await HttpContext.Response.WriteAsync("[");

            for (var i = 0; i < files.Count; i++)
            {
                var width  = 0;
                var height = 0;
                var file   = new FileInfo(files[i]);
                if (GetFileType(file.Extension) == "image")
                {
                    try
                    {
                        using (var stream = new FileStream(file.FullName, FileMode.Open))
                        {
                            using (var image = SKBitmap.Decode(stream))
                            {
                                width  = image.Width;
                                height = image.Height;
                            }
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                await HttpContext.Response.WriteAsync($"{{\"p\":\"{directoryPath.TrimEnd('/')}/{file.Name}\",\"t\":\"{Math.Ceiling(GetTimestamp(file.LastWriteTime))}\",\"s\":\"{file.Length}\",\"w\":\"{width}\",\"h\":\"{height}\"}}");

                if (i < files.Count - 1)
                {
                    await HttpContext.Response.WriteAsync(",");
                }
            }
            await HttpContext.Response.WriteAsync("]");
        }
コード例 #24
0
        private SKBitmap DrawBadges(SKBitmap sectionImage, List <SKBitmap> imageList, ChatRenderOptions renderOptions, System.Drawing.Size canvasSize, ref System.Drawing.Point drawPos, PreviewComment previewComment)
        {
            foreach (string badgeString in previewComment.badges)
            {
                byte[]   imageBytes = Convert.FromBase64String(badgeString);
                SKBitmap badgeImage = SKBitmap.Decode(imageBytes);
                using (SKCanvas sectionImageCanvas = new SKCanvas(sectionImage))
                {
                    float  imageRatio = (float)(renderOptions.EmoteScale);
                    float  imageSize  = badgeImage.Width * imageRatio;
                    float  left       = (float)drawPos.X;
                    float  right      = imageSize + left;
                    float  top        = (float)((sectionImage.Height - imageSize) / 2);
                    float  bottom     = imageSize + top;
                    SKRect drawBox    = new SKRect(left, top, right, bottom);
                    sectionImageCanvas.DrawBitmap(badgeImage, drawBox, imagePaint);
                    drawPos.X += (int)Math.Floor(20 * renderOptions.EmoteScale);
                }
            }

            return(sectionImage);
        }
コード例 #25
0
        private async void Button_Click(object sender, EventArgs e)
        {
            var file = await CrossFilePicker.Current.PickFile();

            if (file == null)
            {
                return;
            }

            ClearResult();

            // 選択された画像ファイルを表示
            byte[] fileData = file.DataArray;
            this.Image1.Source
                = ImageSource.FromStream(() => new MemoryStream(fileData, 0, fileData.Length));

            // バーコード読み取り
            // Xamarin.Formsでは色々な方法が考えられるが、ここではSkiaSharpを使う
            using (SKBitmap bitmap = SKBitmap.Decode(fileData))
            {
                ZXing.BarcodeReader reader = new BarcodeReader()
                {
                    AutoRotate = true,
                    Options    = { TryHarder = true },
                };
                //ZXing.Result result = reader.Decode(bitmap);
                // ☟別スレッドでやるときも、UIスレッドで作成したSKBitmapインスタンスを渡してよい
                ZXing.Result result = await Task.Run(() => reader.Decode(bitmap));

                // 注意:☝このDecodeメソッドは拡張メソッドとして実装されている
                // https://github.com/micjahn/ZXing.Net/blob/master/Source/Bindings/ZXing.SkiaSharp/BarcodeReader.Extensions.cs
                // ので、using ZXing; が必須。

                if (result != null)
                {
                    ShowResult(result);
                }
            }
        }
コード例 #26
0
        public ShowAffineMatrixPage()
        {
            InitializeComponent();

            string   resourceID = "SkiaSharpFormsDemos.Media.SeatedMonkey.jpg";
            Assembly assembly   = GetType().GetTypeInfo().Assembly;

            using (Stream stream = assembly.GetManifestResourceStream(resourceID))
                using (SKManagedStream skStream = new SKManagedStream(stream))
                {
                    bitmap = SKBitmap.Decode(skStream);
                }

            touchPoints[0] = new TouchPoint(100, 100);                  // upper-left corner
            touchPoints[1] = new TouchPoint(bitmap.Width + 100, 100);   // upper-right corner
            touchPoints[2] = new TouchPoint(100, bitmap.Height + 100);  // lower-left corner

            bitmapSize = new SKSize(bitmap.Width, bitmap.Height);
            matrix     = ComputeMatrix(bitmapSize, touchPoints[0].Center,
                                       touchPoints[1].Center,
                                       touchPoints[2].Center);
        }
コード例 #27
0
        public void PreblendImagesNetStandard2()
        {
            //ExStart
            //ExFor:PdfSaveOptions.PreblendImages
            //ExSummary:Shows how to preblend images with transparent backgrounds (.NetStandard 2.0).
            Document        doc     = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            using (SKBitmap image = SKBitmap.Decode(ImageDir + "TransparentBG.png"))
            {
                builder.InsertImage(image);
            }

            // Create a PdfSaveOptions object and setting this flag may change the quality and size of the output .pdf
            // because of the way some images are rendered
            PdfSaveOptions options = new PdfSaveOptions();

            options.PreblendImages = true;

            doc.Save(ArtifactsDir + "PdfSaveOptions.PreblendImages.pdf", options);
            //ExEnd
        }
コード例 #28
0
        private static List <Bitmap> GetImage(int width, int height, int iconWidth, int iconHeight, string url)
        {
            List <Bitmap> images = new List <Bitmap>();

            using (WebClient client = new WebClient())
            {
                byte[] data = client.DownloadData(url);
                using (var original = SKBitmap.Decode(data))
                {
                    using (var resized = original.Resize(new SKImageInfo(width, height), SKBitmapResizeMethod.Lanczos3))
                    {
                        images.Add(resized.ToBitmap());
                    }
                    using (var resized = original.Resize(new SKImageInfo(iconWidth, iconHeight), SKBitmapResizeMethod.Lanczos3))
                    {
                        images.Add(resized.ToBitmap());
                    }
                }
            }

            return(images);
        }
コード例 #29
0
        private static async Task <RemoteImageInfo> GetImageSizeAndValidate(RemoteImageInfo item, CancellationToken cancellationToken)
        {
            if (Plugin.Instance.Configuration.DisableImageValidation)
            {
                return(item);
            }

            var http = await HTTP.Request(item.Url, HttpMethod.Head, cancellationToken).ConfigureAwait(false);

            if (http.IsOK)
            {
                if (Plugin.Instance.Configuration.DisableImageSize)
                {
                    return(item);
                }

                http = await HTTP.Request(item.Url, cancellationToken).ConfigureAwait(false);

                if (http.IsOK)
                {
                    using (var img = SKBitmap.Decode(http.ContentStream))
                    {
                        if (img != null && img.Width > 100)
                        {
                            return(new RemoteImageInfo
                            {
                                ProviderName = item.ProviderName,
                                Url = item.Url,
                                Type = item.Type,
                                Height = img.Height,
                                Width = img.Width,
                            });
                        }
                    }
                }
            }

            return(null);
        }
コード例 #30
0
        public async Task ResizeWorkAsync(string filePath, string destPath, double scale)
        {
            var bitmap   = SKBitmap.Decode(filePath);
            var imgPhoto = SKImage.FromBitmap(bitmap);
            var imgName  = Path.GetFileNameWithoutExtension(filePath);

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

            var destinationWidth  = (int)(sourceWidth * scale);
            var destinationHeight = (int)(sourceHeight * scale);

            await Task.Yield();

            using var scaledBitmap = bitmap.Resize(
                      new SKImageInfo(destinationWidth, destinationHeight),
                      SKFilterQuality.High);
            using var scaledImage = SKImage.FromBitmap(scaledBitmap);
            using var data        = scaledImage.Encode(SKEncodedImageFormat.Jpeg, 100);
            using var s           = File.OpenWrite(Path.Combine(destPath, imgName + ".jpg"));
            data.SaveTo(s);
        }