Exemple #1
0
        private void OnExecute()
        {
            var tileWidth  = Int32.Parse(Tiles.Split("x")[0]);
            var tileHeight = Int32.Parse(Tiles.Split("x")[1]);

            var rect = new SixLabors.Primitives.Rectangle(0, 0, tileWidth, tileHeight);

            using (var img = Image.Load(Input))
            {
                var index = 0;
                var stepX = img.Width / tileWidth;
                var stepY = img.Height / tileHeight;

                var dir = Output ?? System.Environment.CurrentDirectory;

                for (int y = 0; y < stepY; y++)
                {
                    for (int x = 0; x < stepX; x++)
                    {
                        rect.X = x * tileWidth;
                        rect.Y = y * tileHeight;

                        using (var sub = img.Clone(ctx => ctx.Crop(rect)))
                        {
                            sub.Save(System.IO.Path.Combine(dir, $"image-{index}.png"));
                        }

                        index++;
                    }
                }
            }
        }
Exemple #2
0
            public Image <Rgba32> GetBitmap()
            {
                if (PcsObjects.Count == 1)
                {
                    return(SupDecoder.DecodeImage(PcsObjects[0], BitmapObjects[0], PaletteInfos));
                }

                var r = Rectangle.Empty;

                for (var ioIndex = 0; ioIndex < PcsObjects.Count; ioIndex++)
                {
                    var ioRect = new Rectangle(PcsObjects[ioIndex].Origin, BitmapObjects[ioIndex][0].Size);
                    r = r.IsEmpty ? ioRect : Rectangle.Union(r, ioRect);
                }

                var mergedBmp = new Image <Rgba32>(r.Width, r.Height);

                for (var ioIndex = 0; ioIndex < PcsObjects.Count; ioIndex++)
                {
                    var offset = PcsObjects[ioIndex].Origin - new Size(r.Location);
                    using (var singleBmp = SupDecoder.DecodeImage(PcsObjects[ioIndex], BitmapObjects[ioIndex], PaletteInfos))
                    {
                        mergedBmp.Mutate(b => b.DrawImage(singleBmp, offset, 0));
                    }
                }
                return(mergedBmp);
            }
Exemple #3
0
        public Image <Rgba32> RenderAsGif(int width = 320, int height = 120)
        {
            using (var image = new Image <Rgba32>(width, height))
            {
                int margin = 7, barwidth = width / 5;
                for (int i = 0; i < bitarray.Count; i++)
                {
                    for (int cl = 1; cl >= 0; cl--)
                    {
                        int[] bits = this.bitarray[i];
                        bits[0] = cl;
                        using (var frame = new Image <Rgba32>(width, height))
                        {
                            for (int b = 0; b < 5; b++)
                            {
                                var color  = bitarray[i][b] == 1 ? Rgba32.White : Rgba32.Black;
                                var bounds = new CoreRectangle(b * barwidth + margin, margin, barwidth - 2 * margin, height - 2 * margin);
                                frame.Mutate(x => x.Fill(color, bounds));
                            }
                            image.Frames.AddFrame(frame.Frames[0]);
                        }
                    }
                }

                return(image);
            }
        }
        public void FillOffCanvas()
        {
            SixLabors.Primitives.Rectangle bounds = new SixLabors.Primitives.Rectangle(-100, -10, 10, 10);

            Mock <IBrush <Rgba32> > brush  = new Mock <IBrush <Rgba32> >();
            Mock <Region>           region = new Mock <Region>();

            region.Setup(x => x.Bounds).Returns(bounds);

            region.Setup(x => x.MaxIntersections).Returns(10);
            region.Setup(x => x.Scan(It.IsAny <float>(), It.IsAny <float[]>(), It.IsAny <int>()))
            .Returns <float, Span <float> >((y, span) =>
            {
                if (y < 5)
                {
                    span[0] = -10f;
                    span[1] = 100f;
                    return(2);
                }
                return(0);
            });

            GraphicsOptions options = new GraphicsOptions(true)
            {
            };
            FillRegionProcessor <Rgba32> processor = new FillRegionProcessor <Rgba32>(brush.Object, region.Object, options);
            Image <Rgba32> img = new Image <Rgba32>(10, 10);

            processor.Apply(img, bounds);
        }
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context)
        {
            #region Preparation

            var imageUrl = req.Query["imageUrl"];

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            var faceEndpoint    = config["faceEndpoint"];
            var subscriptionKey = config["faceSubscriptionKey"];
            #endregion

            FaceClient faceClient = new FaceClient(new ApiKeyServiceClientCredentials(subscriptionKey), new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = faceEndpoint
            };
            IList <DetectedFace> faceList = await faceClient.Face.DetectWithUrlAsync(imageUrl, true, true);

            #region Output
            var        firstFace = faceList.FirstOrDefault();
            HttpClient client    = new HttpClient();
            byte[]     buffer    = await client.GetByteArrayAsync(imageUrl);

            System.IO.MemoryStream imageStream = new System.IO.MemoryStream();
            SixLabors.ImageSharp.Formats.IImageFormat format;

            using (Image image = Image.Load(buffer, out format))
            {
                var centerWidth  = image.Width / 2;
                var centerHeight = image.Height / 2;

                var eyeSize = firstFace.FaceLandmarks.EyeLeftInner.X - firstFace.FaceLandmarks.EyeLeftOuter.X;

                var blurRectangle = new SixLabors.Primitives.Rectangle(
                    System.Convert.ToInt32(firstFace.FaceLandmarks.EyeLeftOuter.X - eyeSize),
                    System.Convert.ToInt32(firstFace.FaceLandmarks.EyeLeftOuter.Y - eyeSize),
                    System.Convert.ToInt32(firstFace.FaceLandmarks.EyeRightOuter.X + eyeSize - (firstFace.FaceLandmarks.EyeLeftOuter.X - eyeSize)),
                    System.Convert.ToInt32(firstFace.FaceLandmarks.EyeRightOuter.Y + eyeSize - (firstFace.FaceLandmarks.EyeLeftOuter.Y - eyeSize)));

                image.Mutate(x => x
                             .BokehBlur(blurRectangle));

                image.Save(imageStream, format);
            }

            return(new FileContentResult(imageStream.ToArray(), "image/jpeg"));

            #endregion
        }
Exemple #6
0
        private List <KeyValuePair <int, string> > ProcesSplitImages(string ImageId, string srcOriginalImage, string destinationFolderName)
        {
            int cols = 5;
            int rows = 5;
            //int width = 600;
            //int height = 600;

            var sfileSplit = new List <KeyValuePair <int, string> >();

            using (Image <Rgba32> img = Image.Load(srcOriginalImage))
            {
                // var imgDummy = img.Clone();
                //if (img.Width > 600 || img.Height > 600)
                //{
                //    imgDummy = img.Clone(x =>
                //     x.Resize(new ResizeOptions
                //     {
                //         Mode = ResizeMode.Max,
                //         Position = AnchorPositionMode.Center,
                //         Size = new SixLabors.Primitives.Size(width, height),
                //         Compand = false
                //     }));
                //}

                int    _img_width  = img.Width;
                int    _img_height = img.Height;
                string filename    = System.IO.Path.GetFileNameWithoutExtension(srcOriginalImage);
                var    indexFile   = 0;
                for (int x = 0; x < cols; x++)
                {
                    for (int y = 0; y < rows; y++)
                    {
                        indexFile += 1;
                        var cropArea = new SixLabors.Primitives.Rectangle(x * (_img_width / cols), y * (_img_height / rows), _img_width / cols, _img_height / rows);
                        var newImg   = img.Clone(e => e.Crop(cropArea));

                        var    x_fileName = string.Format("PLS{0}_x{1}_{2}.jpg", ImageId, x, y);
                        string pathSave   = @"" + destinationFolderName.TrimEnd('/') + "/" + x_fileName;

                        newImg.Save(pathSave, new JpegEncoder {
                            Quality = 100
                        });
                        sfileSplit.Add(new KeyValuePair <int, string>(indexFile, pathSave));
                    }
                }
            }

            return(sfileSplit);
        }
Exemple #7
0
        public System.IO.Stream GetImageDetail(System.IO.Stream imageStream, int x, int y, int width, int heigth)
        {
            #region validation

            if (imageStream == null)
            {
                throw new ArgumentNullException(nameof(imageStream));
            }

            #endregion

            using (Image <Rgba32> originalImage = LoadImageFromStream(imageStream))
            {
                // sometimes bounding boxes will be larger then image.
                // so we will shrink size of bounding box until they are matching our requirements

                if (x < 0)
                {
                    x = 0;
                }
                if (y < 0)
                {
                    y = 0;
                }
                if (x + width > originalImage.Width)
                {
                    width = originalImage.Width - x;
                }
                if (y + heigth > originalImage.Height)
                {
                    heigth = originalImage.Height - y;
                }

                SixLabors.Primitives.Rectangle boundingBox = new SixLabors.Primitives.Rectangle()
                {
                    X      = x,
                    Y      = y,
                    Width  = width,
                    Height = heigth
                };

                using (Image <Rgba32> targetImage = originalImage.Clone())
                {
                    targetImage.Mutate(ctx => ctx.Crop(boundingBox));

                    return(SaveAsStream(targetImage));
                }
            }
        }
        [InlineData(false, 16, 4)] // we always do 4 sub=pixels when antialising is off.
        public void MinimumAntialiasSubpixelDepth(bool antialias, int antialiasSubpixelDepth, int expectedAntialiasSubpixelDepth)
        {
            SixLabors.Primitives.Rectangle bounds = new SixLabors.Primitives.Rectangle(0, 0, 1, 1);

            Mock <IBrush <Rgba32> > brush  = new Mock <IBrush <Rgba32> >();
            Mock <Region>           region = new Mock <Region>();

            region.Setup(x => x.Bounds).Returns(bounds);

            GraphicsOptions options = new GraphicsOptions(antialias)
            {
                AntialiasSubpixelDepth = 1
            };
            FillRegionProcessor <Rgba32> processor = new FillRegionProcessor <Rgba32>(brush.Object, region.Object, options);
            Image <Rgba32> img = new Image <Rgba32>(1, 1);

            processor.Apply(img, bounds);

            region.Verify(x => x.Scan(It.IsAny <float>(), It.IsAny <float[]>(), It.IsAny <int>()), Times.Exactly(4));
        }
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            log.Info("Image data received.");

            var kvp           = req.GetQueryParameterDictionary();
            int x             = Convert.ToInt32(kvp["x"]);
            int y             = Convert.ToInt32(kvp["y"]);
            int height        = Convert.ToInt32(kvp["height"]);
            int width         = Convert.ToInt32(kvp["width"]);
            var cropRectangle = new SixLabors.Primitives.Rectangle(x, y, width, height);

            byte[] data;
            string requestBody = new StreamReader(req.Body).ReadToEnd();

            if (requestBody.StartsWith("\\"))
            {
                data = File.ReadAllBytes(requestBody);
            }
            else
            {
                data = (byte[])JsonConvert.DeserializeObject(requestBody);
            }

            log.Info("Starting crop.");
            using (Image <Rgba32> image = Image.Load(data))
            {
                var clone = image.Clone();
                clone.Mutate(c => c.Crop(cropRectangle));

                // Run pixel detection
                log.Info("Determining black pixel count.");
                var blackPixelCount = CountPixels(clone, new Rgba32(255, 0, 0, 0));

                log.Info("Requesting OCR.");
                var text = await GetOcrText(data);

                return(new OkObjectResult(new { pixelCount = blackPixelCount, capturedText = text }));
            }
        }
Exemple #10
0
        /// <summary>
        /// Blur faces inside the given rectangular areas.
        /// </summary>
        /// <param name="faceRects">Rectangles defining the areas to be blurred.</param>
        /// <param name="sourceImage">The original image to blur.</param>
        private void BlurFaces(FaceRectangle[] faceRects, string sourceImage)
        {
            Image <Rgba32> image;

            using (FileStream stream = File.OpenRead(sourceImage))
            {
                image = SixLabors.ImageSharp.Image.Load(stream);
                IPen <Rgba32> pen = new Pen <Rgba32>(new SolidBrush <Rgba32>(Rgba32.Red), 2);
                foreach (var faceRect in faceRects)
                {
                    var rectangle = new SixLabors.Primitives.Rectangle(
                        faceRect.Left,
                        faceRect.Top,
                        faceRect.Width,
                        faceRect.Height);
                    image.Mutate(img =>
                    {
                        img.BoxBlur <Rgba32>(20, rectangle);
                        img.Draw(pen, rectangle);
                    });
                }
            }

            // stackoverflow.com/questions/5782913/how-to-convert-from-type-image-to-type-bitmapimage
            MemoryStream memoryStream = new MemoryStream();

            image.Save(memoryStream, new SixLabors.ImageSharp.Formats.Png.PngEncoder());
            BitmapImage bitmap = new BitmapImage();

            bitmap.BeginInit();
            //bitmap.CacheOption = BitmapCacheOption.OnLoad;
            // bitmap.UriSource = null;
            bitmap.StreamSource = memoryStream;
            bitmap.EndInit();

            PhotoSource = bitmap;
        }
Exemple #11
0
        private void TODO(string path)
        {
            SixLabors.ImageSharp.Image <SixLabors.ImageSharp.Rgba32> img =
                SixLabors.ImageSharp.Image.Load(path);

            img.Mutate(x => x.Grayscale());
            img.Mutate(x => x.BlackWhite());
            img.Mutate(x => x.Invert());

            img.Mutate(x => x.Flip(FlipType.Horizontal));

            img.Mutate(x => x.RotateFlip(RotateType.Rotate270, FlipType.None));

            float degrees = 30;

            img.Mutate(x => x.Rotate(degrees, KnownResamplers.Bicubic));


            float degreesX = 5, degreesY = 5;

            img.Mutate(x => x.Skew(degreesX, degreesY, KnownResamplers.Bicubic));


            img.Mutate(x => x.OilPaint());
            img.Mutate(x => x.Sepia());


            img.Mutate(x => x.Pixelate());


            SixLabors.Primitives.Rectangle bounds            =
                new SixLabors.Primitives.Rectangle(10, 10, img.Width / 2, img.Height / 2);
            img.Mutate(x => x.BackgroundColor(SixLabors.ImageSharp.PixelFormats.NamedColors <
                                                  SixLabors.ImageSharp.Rgba32> .HotPink, bounds));

            img.Mutate(x => x.GaussianBlur());
            img.Mutate(x => x.GaussianSharpen());
            img.Mutate(x => x.DetectEdges());


            img.Mutate(x => x.Glow());
            img.Mutate(x => x.Vignette());


            SixLabors.ImageSharp.Dithering.IOrderedDither defaultDitherer =
                new SixLabors.ImageSharp.Dithering.OrderedDither();
            img.Mutate(x => x.Dither(defaultDitherer));

            SixLabors.ImageSharp.Dithering.IErrorDiffuser ad =
                new SixLabors.ImageSharp.Dithering.AtkinsonDiffuser();
            float threshold = 0.5f;

            img.Mutate(x => x.Dither(ad, threshold));


            SixLabors.Primitives.Rectangle thresholdBounds =
                new SixLabors.Primitives.Rectangle(10, 10, img.Width / 2, img.Height / 2);
            float thresholdValue = 0.5f;

            img.Mutate(x => x.BinaryThreshold(thresholdValue, thresholdBounds));


            int value = 5;

            SixLabors.Primitives.Rectangle blurBounds =
                new SixLabors.Primitives.Rectangle(10, 10, img.Width / 2, img.Height / 2);
            img.Mutate(x => x.BoxBlur(value, blurBounds));

            img.Mutate(x => x.ColorBlindness(ColorBlindness.Tritanopia));
        }