/// <summary>
        /// Add a password to the image.
        /// </summary>
        /// <param name="curImg">Image to add password to.</param>
        /// <param name="pass">Password to add to top left corner.</param>
        /// <returns>Image with the password in the top left corner.</returns>
        private (Stream, string) AddPassword(byte[] curImg, string pass)
        {
            // draw lower, it looks better
            pass = pass.TrimTo(10, true).ToLowerInvariant();
            using (var img = Image.Load(curImg, out var format))
            {
                // choose font size based on the image height, so that it's visible
                var font = _fonts.NotoSans.CreateFont(img.Height / 12, FontStyle.Bold);
                img.Mutate(x =>
                {
                    // measure the size of the text to be drawing
                    var size = TextMeasurer.Measure(pass, new RendererOptions(font, new PointF(0, 0)));

                    // fill the background with black, add 5 pixels on each side to make it look better
                    x.FillPolygon(Rgba32.FromHex("00000080"),
                                  new PointF(0, 0),
                                  new PointF(size.Width + 5, 0),
                                  new PointF(size.Width + 5, size.Height + 10),
                                  new PointF(0, size.Height + 10));

                    // draw the password over the background
                    x.DrawText(pass,
                               font,
                               Brushes.Solid(Rgba32.White),
                               new PointF(0, 0));
                });
                // return image as a stream for easy sending
                return(img.ToStream(format), format.FileExtensions.FirstOrDefault() ?? "png");
            }
        }
Esempio n. 2
0
        internal List <Pixel> ReadImage(string path)
        {
            var result = new List <Pixel>();

            byte[] imageBytes = null;
            using (var image = ImageSharp.Load(path))
            {
                imageBytes = ImageExtension.SavePixelData(image);
                for (int x = 0; x < image.Width; x++)
                {
                    for (int y = 0; y < image.Height; y++)
                    {
                        var baseIndex = (x + (y * image.Width)) * 4;
                        if (imageBytes[baseIndex + 3] > 0)
                        {
                            result.Add(new Pixel()
                            {
                                X = x,
                                Y = y,
                                R = imageBytes[baseIndex],
                                G = imageBytes[baseIndex + 1],
                                B = imageBytes[baseIndex + 2],
                                A = imageBytes[baseIndex + 3]
                            });
                        }
                    }
                }
            }
            return(result);
        }
Esempio n. 3
0
 public void ReadImages()
 {
     if (this.bmpStream == null)
     {
         this.bmpStream          = File.OpenRead(Path.Combine(TestEnvironment.InputImagesDirectoryFullPath, TestImages.Bmp.Car));
         this.bmpCore            = CoreImage.Load <Rgba32>(this.bmpStream);
         this.bmpStream.Position = 0;
     }
 }
Esempio n. 4
0
 public CoreSize JpegImageSharpPdfJs()
 {
     using (MemoryStream memoryStream = new MemoryStream(this.jpegBytes))
     {
         using (Image <Rgba32> image = CoreImage.Load <Rgba32>(memoryStream, new PdfJsJpegDecoder()))
         {
             return(new CoreSize(image.Width, image.Height));
         }
     }
 }
Esempio n. 5
0
 public void ReadImages()
 {
     if (this.bmpStream == null)
     {
         this.bmpStream          = File.OpenRead("../ImageSharp.Tests/TestImages/Formats/Bmp/Car.bmp");
         this.bmpCore            = CoreImage.Load <Rgba32>(this.bmpStream);
         this.bmpStream.Position = 0;
         this.bmpDrawing         = Image.FromStream(this.bmpStream);
     }
 }
        /// <summary>
        /// Load the IMG as Color 2byte list
        /// </summary>
        /// <param name="filename">The Filepath/Filenamee to load</param>
        /// <param name="width">The width from the IMG</param>
        /// <param name="height">The Height from the IMG</param>
        /// <param name="animatedColor">Needed if alpha is 0 or 1</param>
        /// <param name="pixelsize">Pixelsize of a pixel needed for Colortable</param>
        /// <returns></returns>
        internal static List <UInt16> LoadImage(String filename, ref int width, ref int height, int animatedColor = 1, int pixelsize = 1, uint type = 0, int offsetx = 0, int offsety = 0)
        {
            if (Logger.Loggeractiv)
            {
                Logger.Log("LoadImage");
            }
            List <UInt16> colors = new List <UInt16>();

            try
            {
                var image = Image.Load(filename);
                if (width == 0)
                {
                    width = image.Width;
                }
                if (height == 0)
                {
                    height = image.Height;
                }
                for (int y = offsety; y < height + offsety; y += pixelsize)
                {
                    for (int x = offsetx; x < width + offsetx; x += pixelsize) //Bgra8888
                    {
                        var  pixel = image[x, y];
                        byte a     = (animatedColor >= 1 ||
                                      ((GM1FileHeader.DataType)type) == GM1FileHeader.DataType.TilesObject ||
                                      ((GM1FileHeader.DataType)type) == GM1FileHeader.DataType.Animations ||
                                      ((GM1FileHeader.DataType)type) == GM1FileHeader.DataType.TGXConstSize ||
                                      ((GM1FileHeader.DataType)type) == GM1FileHeader.DataType.NOCompression ||
                                      ((GM1FileHeader.DataType)type) == GM1FileHeader.DataType.NOCompression1) ? byte.MaxValue : byte.MinValue;
                        if (pixel.A == 0)
                        {
                            colors.Add((ushort)32767);
                        }
                        else
                        {
                            colors.Add(EncodeColorTo2Byte((uint)(pixel.B | pixel.G << 8 | pixel.R << 16 | a << 24)));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (Logger.Loggeractiv)
                {
                    Logger.Log("Exception:\n" + e.Message);
                }
                MessageBoxWindow messageBox = new MessageBoxWindow(MessageBoxWindow.MessageTyp.Info, "Something went wrong: pls add a issue on the Github Page\n\nError:\n" + e.Message);
                messageBox.Show();
            }
            return(colors);
        }
Esempio n. 7
0
        public void ReadImages()
        {
            if (this.bmpStream == null)
            {
                string path = this.LargeImage
                    ? "../ImageSharp.Tests/TestImages/Formats/Jpg/baseline/jpeg420exif.jpg"
                    : "../ImageSharp.Tests/TestImages/Formats/Bmp/Car.bmp";

                this.bmpStream          = File.OpenRead(path);
                this.bmpCore            = CoreImage.Load <Rgba32>(this.bmpStream);
                this.bmpStream.Position = 0;
            }
        }
        internal unsafe static WriteableBitmap LoadImageAsBitmap(String filename, ref int width, ref int height, int offsetx = 0, int offsety = 0)
        {
            if (Logger.Loggeractiv)
            {
                Logger.Log("LoadImage");
            }
            var image = Image.Load(filename);

            if (width == 0)
            {
                width = image.Width;
            }
            if (height == 0)
            {
                height = image.Height;
            }
            WriteableBitmap bitmap = new WriteableBitmap(new PixelSize(width, height), new Vector(300, 300), Avalonia.Platform.PixelFormat.Rgba8888);

            using (var bit = bitmap.Lock())
            {
                try
                {
                    int xBit = 0, yBit = 0;
                    for (int y = offsety; y < height + offsety; y++)
                    {
                        for (int x = offsetx; x < width + offsetx; x++) //Bgra8888
                        {
                            var pixel = image[x, y];

                            var ptr = (uint *)bit.Address;
                            ptr += (uint)((bitmap.PixelSize.Width * yBit) + xBit);
                            *ptr = pixel.PackedValue;
                            xBit++;
                        }
                        xBit = 0;
                        yBit++;
                    }
                }
                catch (Exception e)
                {
                    if (Logger.Loggeractiv)
                    {
                        Logger.Log("Exception:\n" + e.Message);
                    }
                    MessageBoxWindow messageBox = new MessageBoxWindow(MessageBoxWindow.MessageTyp.Info, "Something went wrong: pls add a issue on the Github Page\n\nError:\n" + e.Message);
                    messageBox.Show();
                }
            }

            return(bitmap);
        }
        /// <summary>
        /// The event handler for the option image button clicked
        /// </summary>
        private void OptionImageButton_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG"
            };


            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _selectedModOption.Image         = Image.Load(openFileDialog.FileName);
                _selectedModOption.ImageFileName = openFileDialog.FileName;
                OptionImage.Source = new BitmapImage(new Uri(openFileDialog.FileName));
            }
        }
Esempio n. 10
0
        public NewEntryView()
        {
            this.InitializeComponent();

            this.DataContext = this;

            this.WhenActivated(disposables =>
            {
                this.BindCommand(ViewModel,
                                 vm => vm.AddPhotoCommand,
                                 v => v.AddPhoto)
                .DisposeWith(disposables);

                this.OneWayBind(ViewModel,
                                vm => vm.Photos,
                                v => v.Photos.ItemsSource,
                                vmToViewConverterOverride: new BitmapImageConverter())
                .DisposeWith(disposables);

                this.ViewModel?.AddPhoto
                .RegisterHandler(async interaction =>
                {
                    var picker      = new FileOpenPicker();
                    picker.ViewMode = PickerViewMode.Thumbnail;
                    picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
                    picker.FileTypeFilter.Add(".jpg");
                    picker.FileTypeFilter.Add(".jpeg");
                    picker.FileTypeFilter.Add(".png");

                    var photos = await picker.PickMultipleFilesAsync();
                    if (photos != null)
                    {
                        var convertedPhotos = new List <Image>();
                        foreach (var photo in photos)
                        {
                            var stream = await photo.OpenReadAsync();
                            var image  = Image.Load(stream.AsStreamForRead());
                            convertedPhotos.Add(image);
                        }

                        interaction.SetOutput(convertedPhotos);
                    }

                    var aaa = this.Photos.ItemsSource;
                })
                .DisposeWith(disposables);
            });
        }
Esempio n. 11
0
        public static Texture CreateFromFile(string sourcePath)
        {
            Log.Info("Loading: {SourcePath}", sourcePath);
            var   imagePath = AssetManager.GetAssetsPath(sourcePath);
            Image bitmap    = Image.Load(imagePath);

            var txt = new Texture(bitmap.Width, bitmap.Height)
            {
                SourcePath        = sourcePath,
                Label             = Path.GetFileName(sourcePath),
                AutoDisposeBitmap = true,
            };

            txt.SetData(bitmap);
            return(txt);
        }
Esempio n. 12
0
        public unsafe IImage FromStream(Stream s)
        {
            using (var image = Image.Load(s))
            {
                var pixels = new uint[image.Width * image.Height];

                fixed(void *data = &image.Frames[0].DangerousGetPinnableReferenceToPixelBuffer())
                {
                    for (var i = 0; i < pixels.Length; i++)
                    {
                        pixels[i] = ((uint *)data)[i];
                    }
                }

                return(new LoadedImage(image.Width, image.Height, pixels));
            }
        }
Esempio n. 13
0
            protected override void ReadFilesImpl()
            {
                base.ReadFilesImpl();

                foreach (KeyValuePair <string, byte[]> kv in this.FileNamesToBytes)
                {
                    byte[] bytes = kv.Value;
                    string fn    = kv.Key;

                    using (var ms1 = new MemoryStream(bytes))
                    {
                        this.FileNamesToImageSharpImages[fn] = CoreImage.Load <Rgba32>(ms1);
                    }

                    this.FileNamesToSystemDrawingImages[fn] = new Bitmap(new MemoryStream(bytes));
                }
            }
Esempio n. 14
0
        private static void WriteProfile(Document doc)
        {
            var appName    = "全椒麻将 - 应用分析报告";
            var appVersion = "应用版本本:1.0.7";
            var md5        = "文件MD5:db207522f25a10d16d6441d49e620d4e";
            var date       = "分析日期:2020-05-25";

            var logoSize = 60;
            var stream   = Assembly.GetExecutingAssembly().GetManifestResourceStream("Lab.PdfTest.Resources.logo.png");
            var img      = Image.Load(stream);

            img.Mutate(o => o.Resize(logoSize, img.Height * logoSize / img.Width));
            var ms = new MemoryStream();

            img.Save(ms, new BmpEncoder());

            doc.Add(new iText.Layout.Element.Image(ImageDataFactory.Create(ms.GetBuffer()))
                    .SetMarginTop(150)
                    .SetHorizontalAlignment(HorizontalAlignment.CENTER)
                    );

            doc.Add(new Paragraph(appName)
                    .SetFontSize(24)
                    .SetMarginTop(10)
                    .SetTextAlignment(TextAlignment.CENTER)
                    );

            doc.Add(new Paragraph(appVersion)
                    .SetFontSize(15)
                    .SetMarginTop(5)
                    .SetTextAlignment(TextAlignment.CENTER)
                    );

            doc.Add(new Paragraph(md5)
                    .SetFontSize(10)
                    .SetMarginTop(5)
                    .SetTextAlignment(TextAlignment.CENTER)
                    );

            doc.Add(new Paragraph(date)
                    .SetFontSize(10)
                    .SetMarginTop(110)
                    .SetTextAlignment(TextAlignment.CENTER)
                    );
        }
Esempio n. 15
0
        public void ImageSharpResize(string input)
        {
            using (var output = File.Open(OutputPath(input, ImageSharp), FileMode.Create))
            {
                // Resize it to fit a 150x150 square
                using (var image = ImageSharpImage.Load(input))
                {
                    image.Mutate(i => i.Resize(new ResizeOptions
                    {
                        Size = new ImageSharpSize(ThumbnailSize, ThumbnailSize),
                        Mode = ResizeMode.Max
                    }));

                    // Reduce the size of the file
                    image.Metadata.ExifProfile = null;

                    // Save the results
                    image.Save(output, imageSharpJpegEncoder);
                }
            }
        }
Esempio n. 16
0
        // This function will get triggered/executed when a new message is written
        // on an Azure Queue called queue.
        public static void ProcessQueueMessage([ServiceBusTrigger("thumbnails")] BrokeredMessage message, TextWriter log)
        {
            var imgOriginalId = (Guid)message.Properties["imageId"];
            //var imgOriginalId = Newtonsoft.Json.JsonConvert.DeserializeObject<Guid>(b);

            IRepository <Epam.AzureWorkShop.Entities.Image> imgRepo = new ImageRepository();
            var currentImg = imgRepo.GetById(imgOriginalId);

            using (var image = Image.Load(currentImg.Data))
            {
                image.Mutate(i => i.Resize(150, 150));
                using (var outputMemory = new MemoryStream())
                {
                    image.Save(outputMemory, new PngEncoder());

                    var id = imgRepo.Add(new Epam.AzureWorkShop.Entities.Image
                    {
                        Data = outputMemory.ToArray(),
                    }).Id;

                    var metRep  = new MetadataRepository();
                    var metData = metRep.GetByImageId(imgOriginalId);
                    metData.ThumbnailId = id;
                    metRep.Update(metData);

                    using (var httpClient = new HttpClient())
                    {
                        httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["LogicAppUri"]);

                        var content = new FormUrlEncodedContent(new[]
                        {
                            new KeyValuePair <string, string>(nameof(ImageMetadata.FileName), metData.FileName),
                            new KeyValuePair <string, string>(nameof(ImageMetadata.ImageId), metData.ImageId.ToString()),
                            new KeyValuePair <string, string>(nameof(ImageMetadata.ThumbnailId), metData.ThumbnailId.ToString()),
                        });
                        httpClient.PostAsync(ConfigurationManager.AppSettings["LogicAppUri"], content).Wait();
                    }
                }
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Get a random currency image stream, with an optional password sticked onto it.
        /// </summary>
        /// <param name="pass">Optional password to add to top left corner.</param>
        /// <returns>Stream of the currency image</returns>
        public Stream GetRandomCurrencyImage(string pass, out string extension)
        {
            // get a random currency image bytes
            var rng    = new NadekoRandom();
            var curImg = _images.Currency[rng.Next(0, _images.Currency.Count)];

            if (string.IsNullOrWhiteSpace(pass))
            {
                // determine the extension
                using (var img = Image.Load(curImg, out var format))
                {
                    extension = format.FileExtensions.FirstOrDefault() ?? "png";
                }
                // return the image
                return(curImg.ToStream());
            }

            // get the image stream and extension
            var(s, ext) = AddPassword(curImg, pass);
            // set the out extension parameter to the extension we've got
            extension = ext;
            // return the image
            return(s);
        }
        internal static void ImageSharpResize(string path, int size, string outputDirectory)
        {
            using (var input = File.OpenRead(path))
            {
                using (var output = File.Open(OutputPath(path, outputDirectory, ImageSharp), FileMode.Create))
                {
                    // Resize it to fit a 150x150 square
                    using (var image = ImageSharpImage.Load(input))
                    {
                        image.Mutate(i => i.Resize(new ResizeOptions
                        {
                            Size = new ImageSharpSize(size, size),
                            Mode = ResizeMode.Max
                        }));

                        // Reduce the size of the file
                        image.MetaData.ExifProfile = null;

                        // Save the results
                        image.Save(output, imageSharpJpegEncoder);
                    }
                }
            }
        }
Esempio n. 19
0
 public void DecodeJpegImageSharpNwq()
 {
     this.ForEachStream(
         ms => CoreImage.Load <Rgba32>(ms)
         );
 }
        private async void LoadFromButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog {
                Filter = "Texture Files(*.ttmp2)|*.ttmp2", InitialDirectory = Settings.Default.ModPack_Directory
            };

            if (openFileDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            var ttmp     = new TTMP(new DirectoryInfo(Settings.Default.ModPack_Directory), XivStrings.TexTools);
            var ttmpData = await ttmp.GetModPackJsonData(new DirectoryInfo(openFileDialog.FileName));

            if (!ttmpData.ModPackJson.TTMPVersion.Contains("w"))
            {
                FlexibleMessageBox.Show(new Wpf32Window(this),
                                        UIMessages.NotWizardModPack,
                                        UIMessages.ModPackLoadingTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var tempMPD = Path.GetTempFileName();

            using (var archive = ZipFile.OpenRead(openFileDialog.FileName))
            {
                using (var zipStream = archive.GetEntry("TTMPD.mpd").Open())
                {
                    using (var fileStream = new FileStream(tempMPD, FileMode.OpenOrCreate))
                    {
                        await zipStream.CopyToAsync(fileStream);
                    }
                }
            }
            this.ModPackAuthor.Text      = ttmpData.ModPackJson.Author;
            this.ModPackName.Text        = ttmpData.ModPackJson.Name;
            this.ModPackVersion.Text     = ttmpData.ModPackJson.Version;
            this.ModPackDescription.Text = ttmpData.ModPackJson.Description;
            for (var i = modPackWizard.Items.Count - 1; i > 0; i--)
            {
                modPackWizard.Items.RemoveAt(i);
            }
            //var previousPage = modPackWizard.CurrentPage;
            foreach (var wizPageItemJson in ttmpData.ModPackJson.ModPackPages)
            {
                var wizPage = new WizardPage();
                wizPage.Background       = null;
                wizPage.HeaderBackground = null;
                var wizModPackControl = new WizardModPackControl();
                wizPage.Content  = wizModPackControl;
                wizPage.PageType = WizardPageType.Blank;
                foreach (var groupJson in wizPageItemJson.ModGroups)
                {
                    var modGroup = new ModGroup();
                    modGroup.OptionList    = new List <ModOption>();
                    modGroup.GroupName     = groupJson.GroupName;
                    modGroup.SelectionType = groupJson.SelectionType;
                    wizModPackControl.ModGroupList.Add(modGroup);
                    wizModPackControl.ModGroupNames.Add(modGroup.GroupName);
                    foreach (var optionJson in groupJson.OptionList)
                    {
                        var modOption = new ModOption();
                        modGroup.OptionList.Add(modOption);
                        modOption.Name          = optionJson.Name;
                        modOption.GroupName     = optionJson.GroupName;
                        modOption.IsChecked     = optionJson.IsChecked;
                        modOption.SelectionType = optionJson.SelectionType;
                        modOption.Description   = optionJson.Description;
                        if (optionJson.ImagePath.Length > 0)
                        {
                            using (var zipFile = ZipFile.OpenRead(openFileDialog.FileName))
                            {
                                using (var stream = zipFile.GetEntry(optionJson.ImagePath).Open())
                                {
                                    var tmpImage = Path.GetTempFileName();
                                    using (var imageStream = File.Open(tmpImage, FileMode.OpenOrCreate))
                                    {
                                        await stream.CopyToAsync(imageStream);

                                        imageStream.Position = 0;
                                    }
                                    var fileNameBak = openFileDialog.FileName;
                                    openFileDialog.FileName = tmpImage;
                                    modOption.Image         = Image.Load(openFileDialog.FileName);
                                    modOption.ImageFileName = openFileDialog.FileName;
                                    openFileDialog.FileName = fileNameBak;
                                }
                            }
                        }
                        foreach (var modJson in optionJson.ModsJsons)
                        {
                            var modData = new ModData();
                            modData.Category = modJson.Category;
                            modData.FullPath = modJson.FullPath;
                            modData.Name     = modJson.Name;
                            using (var br = new BinaryReader(File.OpenRead(tempMPD)))
                            {
                                br.BaseStream.Seek(modJson.ModOffset, SeekOrigin.Begin);
                                modData.ModDataBytes = br.ReadBytes(modJson.ModSize);
                            }
                            modOption.Mods.Add(modData.FullPath, modData);
                        }
                        ((List <ModOption>)wizModPackControl.OptionsList.ItemsSource).Add(modOption);
                        var view             = (CollectionView)CollectionViewSource.GetDefaultView(wizModPackControl.OptionsList.ItemsSource);
                        var groupDescription = new PropertyGroupDescription("GroupName");
                        view.GroupDescriptions.Clear();
                        view.GroupDescriptions.Add(groupDescription);
                    }
                    if (modGroup.OptionList.Count > 0 && modGroup.OptionList.Count(it => it.IsChecked) == 0)
                    {
                        modGroup.OptionList[0].IsChecked = true;
                    }
                }

                modPackWizard.Items.Add(wizPage);
                modPackWizard.CanHelp = true;
            }
            modPackWizard.Items.Add(new WizardPage()
            {
                Content          = new WizardModPackControl(),
                PageType         = WizardPageType.Blank,
                Background       = null,
                HeaderBackground = null
            });
        }
        public async Task ProcessRecord(S3EventNotification.S3EventNotificationRecord record, ILambdaContext context)
        {
            var cameraKey = record.S3.Object.Key.Split('/')[1];

            var s3GetResult = await s3.GetObjectAsync(record.S3.Bucket.Name, record.S3.Object.Key);

            var classNamesParameterName             = $"/Cameras/{cameraKey}/ClassNames";
            var sceneCodeParameterName              = $"/Cameras/{cameraKey}/SceneCode";
            var observationBoundingBoxParameterName = $"/Cameras/{cameraKey}/ObservationBoundingBox";

            if (!cameraParameters.ContainsKey(observationBoundingBoxParameterName))
            {
                try
                {
                    var getResult = await ssm.GetParameterAsync(new GetParameterRequest
                    {
                        Name = observationBoundingBoxParameterName
                    });

                    cameraParameters.Add(observationBoundingBoxParameterName, getResult.Parameter.Value);
                    context.Logger.LogLine(
                        $"Set {observationBoundingBoxParameterName} = {cameraParameters[observationBoundingBoxParameterName]}");
                }
                catch (Exception exception)
                {
                    context.Logger.LogLine($"Didn't add parameter. {observationBoundingBoxParameterName}");
                    context.Logger.LogLine(exception.Message);
                }
            }

            if (!cameraParameters.ContainsKey(classNamesParameterName))
            {
                var getResult = await ssm.GetParameterAsync(new GetParameterRequest
                {
                    Name = classNamesParameterName
                });

                cameraParameters.Add(classNamesParameterName, getResult.Parameter.Value);
                context.Logger.LogLine($"Set {classNamesParameterName} = {cameraParameters[classNamesParameterName]}");
            }

            if (!cameraParameters.ContainsKey(sceneCodeParameterName))
            {
                var getResult = await ssm.GetParameterAsync(new GetParameterRequest
                {
                    Name = sceneCodeParameterName
                });

                cameraParameters.Add(sceneCodeParameterName, getResult.Parameter.Value);
                context.Logger.LogLine($"Set {sceneCodeParameterName} = {cameraParameters[sceneCodeParameterName]}");
            }

            var memoryStream = new MemoryStream();
            await s3GetResult.ResponseStream.CopyToAsync(memoryStream);

            // Crop the area of interest.
            // TODO: Get the x, y, w, h from parmeter store.

            var croppedMemoryStream = new MemoryStream();
            var cropImage           = cameraParameters.ContainsKey(observationBoundingBoxParameterName);

            if (cropImage)
            {
                var parts = cameraParameters[observationBoundingBoxParameterName].Split(',');
                memoryStream.Position = 0;
                var sourceImage = Image.Load(memoryStream);
                var x           = int.Parse(parts[0]);
                var y           = int.Parse(parts[1]);
                var lowerX      = int.Parse(parts[2]);
                var lowerY      = int.Parse(parts[3]);
                var w           = lowerX - x;
                var h           = lowerY - y;
                sourceImage.Mutate(i => i.Crop(new Rectangle(x, y, w, h)));

                context.Logger.LogLine("Trying to save croped image.");
                sourceImage.Save(croppedMemoryStream, new JpegEncoder());
                croppedMemoryStream.Position = 0;
            }


            var labelsResult = await rekognition.DetectLabelsAsync(new DetectLabelsRequest
            {
                Image = new Amazon.Rekognition.Model.Image
                {
                    Bytes = cropImage ? croppedMemoryStream : memoryStream
                },
                MaxLabels     = 100,
                MinConfidence = 70
            });

            if (cropImage)
            {
                croppedMemoryStream.Position = 0;
            }
            else
            {
                memoryStream.Position = 0;
            }

            var metricData = new List <MetricDatum>();


            var personMetric = new MetricDatum
            {
                MetricName        = "Confidence",
                StorageResolution = 1,
                TimestampUtc      = DateTime.UtcNow,
                Unit       = StandardUnit.Percent,
                Dimensions = new List <Dimension>
                {
                    new Dimension {
                        Name = "CameraKey", Value = cameraKey
                    },
                    new Dimension {
                        Name = "Source", Value = "Rekognition"
                    },
                    new Dimension {
                        Name = "Label", Value = "Person"
                    }
                }
            };

            if (labelsResult.Labels.Any(label => label.Name == "Person"))
            {
                var confidence = Convert.ToDouble(labelsResult.Labels.Single(l => l.Name == "Person").Confidence);
                personMetric.StatisticValues = new StatisticSet
                {
                    Minimum     = confidence,
                    Maximum     = confidence,
                    SampleCount = 1,
                    Sum         = 1
                };
            }
            else
            {
                personMetric.StatisticValues = new StatisticSet
                {
                    Minimum     = 0,
                    Maximum     = 0,
                    SampleCount = 1,
                    Sum         = 1
                };
            }

            metricData.Add(personMetric);


            var objectDetectionResult = await sageMakerRuntime.InvokeEndpointAsync(new InvokeEndpointRequest
            {
                Accept       = "application/jsonlines",
                ContentType  = "application/x-image",
                EndpointName = cameraParameters[sceneCodeParameterName],
                Body         = cropImage ? croppedMemoryStream : memoryStream
            });

            if (cropImage)
            {
                croppedMemoryStream.Close();
            }
            else
            {
                memoryStream.Close();
            }

            using (var streamReader = new StreamReader(objectDetectionResult.Body))
            {
                var json = streamReader.ReadToEnd();

                context.Logger.Log($"SageMaker Endpoint Result: {json}");

                var predictionResult = JsonConvert.DeserializeObject <dynamic>(json).prediction;

                var classNames  = cameraParameters[classNamesParameterName].Split(',');
                var predictions = new List <Prediction>();
                foreach (var pr in predictionResult)
                {
                    predictions.Add(new Prediction
                    {
                        ClassName  = classNames[Convert.ToInt32(pr[0].Value)],
                        Confidence = Convert.ToDouble(pr[1].Value) * 100
                    });
                }

                foreach (var classNotPredicted in classNames.Where(cn => predictions.All(p => p.ClassName != cn)))
                {
                    predictions.Add(new Prediction
                    {
                        ClassName  = classNotPredicted,
                        Confidence = 0
                    });
                }

                foreach (var classGroup in predictions.GroupBy(p => p.ClassName))
                {
                    metricData.Add(new MetricDatum
                    {
                        MetricName        = "Confidence",
                        StorageResolution = 1,
                        TimestampUtc      = DateTime.UtcNow,
                        Unit       = StandardUnit.Percent,
                        Dimensions = new List <Dimension>
                        {
                            new Dimension {
                                Name = "CameraKey", Value = cameraKey
                            },
                            new Dimension {
                                Name = "Source", Value = cameraParameters[sceneCodeParameterName]
                            },
                            new Dimension {
                                Name = "Label", Value = classGroup.Key
                            }
                        },
                        StatisticValues = new StatisticSet
                        {
                            Minimum     = classGroup.Min(c => c.Confidence),
                            Maximum     = classGroup.Max(c => c.Confidence),
                            Sum         = classGroup.Count(),
                            SampleCount = classGroup.Count()
                        }
                    });
                }
            }

            await cloudWatch.PutMetricDataAsync(new PutMetricDataRequest
            {
                Namespace  = "Cameras",
                MetricData = metricData
            });
        }