private void asTextFileToolStripMenuItem_Click(object sender, EventArgs e)
 {
     saveFileDialog1 = new SaveFileDialog();
     if (saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
         //Open the browsed image and display it
         FileStream   fs     = new FileStream(saveFileDialog1.FileName, FileMode.Create);
         StreamWriter sw     = new StreamWriter(fs);
         int          Width  = ImageOperations.GetWidth(ImageMatrix);
         int          Height = ImageOperations.GetHeight(ImageMatrix);
         sw.WriteLine(Width.ToString());
         sw.WriteLine(Height.ToString());
         for (int i = 0; i < Height; i++)
         {
             for (int j = 0; j < Width; j++)
             {
                 sw.WriteLine(ImageMatrix[i, j].red.ToString());
                 sw.WriteLine(ImageMatrix[i, j].green.ToString());
                 sw.WriteLine(ImageMatrix[i, j].blue.ToString());
             }
         }
         sw.Close();
     }
 }
예제 #2
0
        private void SetArtwork(string imagePath, byte[] imageData)
        {
            // Get the size of the artwork
            if (imageData != null)
            {
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.StreamSource = new MemoryStream(imageData);
                bi.EndInit();
                // Use bi.PixelWidth and bi.PixelHeight instead of bi.Width and bi.Height:
                // bi.Width and bi.Height take DPI into account. We don't want that here.
                this.ArtworkSize = bi.PixelWidth + "x" + bi.PixelHeight;
            }
            else
            {
                this.ArtworkSize = string.Empty;
            }

            // Get the artwork data
            this.Artwork.SetValue(imagePath, imageData);

            this.ArtworkThumbnail = ImageOperations.ByteToBitmapImage(imageData, Convert.ToInt32(Constants.CoverLargeSize), Convert.ToInt32(Constants.CoverLargeSize));
            OnPropertyChanged(() => this.HasArtwork);
        }
예제 #3
0
        public IActionResult Update([FromForm] IFormFile image, [FromForm] string carImageString)
        {
            CarImage carImage = JsonConvert.DeserializeObject <CarImage>(carImageString);

            if (image == null)
            {
                var result = _carImageService.Update(carImage);
                if (result.Success)
                {
                    return(Ok(result));
                }
                return(BadRequest(result));
            }
            else
            {
                string firstURL = _webHostEnvironment.WebRootPath;
                //string firstURL = "http://127.0.0.1:8080";
                string path = firstURL + @"\images\";
                string newFileNameWithGUID = Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
                if (!ImageOperations.DeleteFileFromServer(carImage.ImagePath))
                {
                    return(BadRequest(Messages.FileDeleteError));
                }
                if (!ImageOperations.CopyFileToServer(image, path, newFileNameWithGUID))
                {
                    return(BadRequest(Messages.FileCreateError));
                }
                carImage.ImagePath = path + newFileNameWithGUID;
                var result = _carImageService.Update(carImage);
                if (result.Success)
                {
                    return(Ok(result));
                }
                return(BadRequest(result));
            }
        }
예제 #4
0
 public ImageModifiedEventArgs(ContactModel contactItem, ImageType imageType, ImageOperations imageOperations)
 {
     this.ImageOperations = imageOperations;
     this.ImageType       = imageType;
     this.ContactItem     = contactItem;
 }
예제 #5
0
        public static void draw(int wMax, GraphType g)
        {
            byte[,] dummyImage = ImageOperations.OpenImage("..\\..\\..\\..\\Images\\Uniform_and_Salt_Pepper.bmp");   //Using the "tiger" image as a dummy image to use in filtering.
            //Call: "(int)numMaxWindow_Graph.Value" as wMax value when you call this method (draw).

            ZGraphForm z;
            int        windowSize = 3;

            double[] x;
            double[] y;
            double[] y2;
            int      index = 0;
            int      before;
            int      after;
            int      size = ((wMax - 3) / 2) + 1;

            if (g == GraphType.ADAPTIVE_MEDIAN)
            {
                z = new ZGraphForm("Adaptive Median", "Window Size", "Time");
            }
            else
            {
                z = new ZGraphForm("Alpha Trim", "Window Size", "Time");
            }

            x  = new double[size];
            y  = new double[size];
            y2 = new double[size];

            while (windowSize <= wMax)
            {
                if (g == GraphType.ADAPTIVE_MEDIAN)
                {
                    AdaptiveMedianFilter adptvMdin;
                    //using Quick sort
                    before    = System.Environment.TickCount;
                    adptvMdin = new AdaptiveMedianFilter(dummyImage, windowSize);
                    adptvMdin.Filter(SortingType.QUICK_SORT);
                    after    = System.Environment.TickCount;
                    y[index] = after - before;

                    //using Counting Sort sort
                    int before2 = System.Environment.TickCount;
                    adptvMdin = new AdaptiveMedianFilter(dummyImage, windowSize);
                    adptvMdin.Filter(SortingType.COUNTING_SORT);
                    int after2 = System.Environment.TickCount;
                    y2[index] = after2 - before2;
                }

                else
                {
                    /*OPERATION*/
                    AlphaTrimFilter alphaTrim = new AlphaTrimFilter(dummyImage);    //Using a dummy/empty image here instead of 'ImageMatrix' (the real image object).

                    //Using KTH ELEMENT:
                    before = System.Environment.TickCount;
                    alphaTrim.removeNoise(windowSize, 4, SortingType.KTH_ELEMENT);  /*The 0 here is the trim value, constant.*/
                    after    = System.Environment.TickCount;
                    y[index] = after - before;

                    //Using COUNTING SORT:
                    before = System.Environment.TickCount;
                    alphaTrim.removeNoise(windowSize, 4, SortingType.COUNTING_SORT);
                    after     = System.Environment.TickCount;
                    y2[index] = after - before;
                }
                x[index]    = windowSize;
                windowSize += 2;
                index++;
            }
            if (g == GraphType.ADAPTIVE_MEDIAN)
            {
                z.add_curve("Quick Sort", x, y, System.Drawing.Color.Black);
                z.add_curve("Counting Sort", x, y2, System.Drawing.Color.Crimson);
            }
            else
            {
                z.add_curve("Kth Element", x, y, System.Drawing.Color.Black);
                z.add_curve("Counting Sort", x, y2, System.Drawing.Color.Crimson);
            }
            z.Show();
        }
예제 #6
0
        public async Task <IActionResult> Update([FromBody] ADFullDataModel model, Guid ID)
        {
            #region Check user
            var userID = HttpContext.User.Identity.Name;
            if (userID == null)
            {
                return(StatusCode(StatusCodes.Status401Unauthorized));
            }
            ApplicationUser user = await _context.Set <ApplicationUser>().SingleOrDefaultAsync(item => item.UserName == userID);

            Account account = _context.Set <Account>()
                              .Include(x => x.ADs)
                              .FirstOrDefault(x => x.ID == user.AccountID);
            if (user == null || account == null)
            {
                return(null);
            }
            #endregion

            if (model == null || ModelState.IsValid == false)
            {
                return(BadRequest("Unvalid data model"));
            }

            var UpAd = _context.Set <AD>()
                       .Include(x => x.Category)
                       .Include(x => x.Account)
                       .Include(x => x.ADExtraFields)
                       .Include(x => x.ADImages)
                       .SingleOrDefault(s => s.ID == ID);
            if (UpAd == null)
            {
                return(BadRequest("No Ad related to this ID"));
            }

            try
            {
                UpAd.CategoryID   = model.CategoryID;
                UpAd.Name         = model.Name;
                UpAd.Title        = model.Title;
                UpAd.Description  = model.Description;
                UpAd.Email        = model.Email;
                UpAd.Phone        = model.Phone;
                UpAd.IsDisabled   = false;
                UpAd.Price        = model.Price ?? 0;
                UpAd.Longitude    = model.Longitude;
                UpAd.Latitude     = model.Latitude;
                UpAd.IsNegotiable = model.IsNegotiable;
                UpAd.CurrencyID   = _context.Set <Currency>().FirstOrDefault(x => x.Code == model.CurrencyName)?.ID;

                _context.Set <AdExtraField>().RemoveRange(UpAd.ADExtraFields);
                _context.Set <ADImage>().RemoveRange(UpAd.ADImages);

                #region Update Category fields
                if (model.CategoryFieldOptions != null && model.CategoryFieldOptions.Count > 0)
                {
                    foreach (var item in model.CategoryFieldOptions)
                    {
                        var CatField = _context.Set <CategoryField>().Include(x => x.CategoryFieldOptions).SingleOrDefault(S => S.ID == item.CategoryFieldID);
                        CategoryFieldOption catOption = CatField.CategoryFieldOptions.FirstOrDefault(x => x.ID == item.CategoryFieldOptionID);
                        if (CatField == null)
                        {
                            continue;
                        }
                        UpAd.ADExtraFields.Add(new AdExtraField
                        {
                            CategoryFieldOptionID = catOption?.ID,
                            Value = catOption?.Name ?? item.Value,
                            Name  = CatField.Name
                        });
                    }
                }
                #endregion

                #region Update main images
                if (model.MainImage != null && model.MainImage.Length > 0)
                {
                    string filename = ImageOperations.SaveImage(model.MainImage, UpAd);
                    if (!string.IsNullOrWhiteSpace(filename))
                    {
                        UpAd.ADImages.Add(new ADImage()
                        {
                            ImagePath = filename,
                            IsMain    = true
                        });
                    }
                }
                #endregion

                #region Save Other images
                if (model.Images != null && model.Images.Any(x => x.Length > 0))
                {
                    foreach (var file in model.Images.Where(x => x.Length > 0))
                    {
                        string filename = ImageOperations.SaveImage(file, UpAd);
                        if (!string.IsNullOrWhiteSpace(filename))
                        {
                            UpAd.ADImages.Add(new ADImage()
                            {
                                ImagePath = filename,
                                IsMain    = false
                            });
                        }
                    }
                }
                #endregion

                await _context.SubmitAsync();

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
예제 #7
0
 void Start()
 {
     //theSprites = Resources.LoadAll("icons", typeof(Sprite));
     imageOperations = gameObject.AddComponent<ImageOperations> ();
     video = gameObject.GetComponent<VideoGrid> ();
     StartCoroutine (start_(theSprites));
 }
예제 #8
0
        public IActionResult Operate(ArticleFormModel model, IFormFile image)
        {
            if (ModelState.IsValid)
            {
                if (model.Id == 0 || model.Id == null)
                {
                    try
                    {
                        if (image != null)
                        {
                            string imageBase64Data = ImageOperations.GetBase64FromFile(image);
                            model.Image = imageBase64Data;
                        }
                        Article article = new Article
                        {
                            ColorId     = model.ColorId,
                            Detail      = model.Detail,
                            Image       = model.Image,
                            LongDetail  = model.LongDetail,
                            PageName    = model.PageName,
                            ScreenOrder = model.ScreenOrder,
                            SubTitle    = model.SubTitle,
                            Title       = model.Title
                        };

                        db.Add(article);
                        db.SaveChanges();
                        return(StatusCode(200, "Eklendi"));
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("error", "Error! An error occurred while album creating");
                    }
                }
                else
                {
                    var article = db.Article.Where(q => q.Id == model.Id).FirstOrDefault();
                    if (article == null)
                    {
                        ModelState.AddModelError("error", "Unknown Request!");
                    }
                    else
                    {
                        if (image != null)
                        {
                            string imageBase64Data = ImageOperations.GetBase64FromFile(image);
                            article.Image = imageBase64Data;
                        }
                        article.Title       = model.Title;
                        article.SubTitle    = model.SubTitle;
                        article.ScreenOrder = model.ScreenOrder;
                        article.PageName    = model.PageName;
                        article.LongDetail  = model.LongDetail;
                        article.Detail      = model.Detail;
                        article.ColorId     = model.ColorId;
                        db.Update(article);
                        db.SaveChanges();
                        return(StatusCode(200, "Güncellendi!"));
                    }
                }
            }
            return(BadRequest(new
            {
                Message = "Some error(s) occurred!",
                StatusCode = 400,
                ModelState = ModelState.ToList()
            }));
        }
 public OpForm()
 {
     InitializeComponent();
     ImageOperations.DisplayImage(Program.OriginalImage, pictureBox1);
 }
예제 #10
0
 private void ArithmeticFilter(int maskSize)
 {
     ImageOperations.ArithmeticFilter(SelectedImage.Bitmap, maskSize);
 }
예제 #11
0
 private void ModifyHistogram(int gMin, int gMax)
 {
     ImageOperations.ModifyHistogram(SelectedImage.Bitmap, gMin, gMax);
 }
예제 #12
0
 private void RosenfeldOperator(int R)
 {
     ImageOperations.RosenfeldOperator(SelectedImage.Bitmap, R);
 }
 private async void EncodeImage(long initialSeed, byte tap, byte numberOfBits, bool alpha)
 {
     if (!alpha)
     {
         Register  register   = new Register(initialSeed, tap, numberOfBits); // O(1)
         long      pixelsDone = 0;                                            // UI
         Stopwatch watch      = new Stopwatch();                              //UI
         lblTimeTaken.Visible = true;                                         //UI
         lblStatus.Text       = "Encoding Image...";
         watch.Start();                                                       //UI
         for (int i = 0; i < ImageHeight; i++)                                // O(N^2)
         {
             await Task.Run(() =>
             {
                 for (int j = 0; j < ImageWidth; j++)                    //O(N^2)
                 {
                     ImageMatrix[i, j].red   ^= (byte)register.StepK(8); // O(1)
                     ImageMatrix[i, j].green ^= (byte)register.StepK(8); //O(1)
                     ImageMatrix[i, j].blue  ^= (byte)register.StepK(8); //O(1)
                     pixelsDone++;                                       // UI
                 }
             }).
             ContinueWith((ant) =>
             {
                 //lblStatus.Text = "Encoding " + pixelsDone + " pixels / " + (ImageHeight * ImageWidth) + " pixels : " + ((long)(pixelsDone * 100) / (ImageHeight * ImageWidth))
                 string te         = watch.Elapsed.ToString(@"m\:ss");
                 lblTimeTaken.Text = "Time Elapsed : " + te;
             }
                          , TaskScheduler.FromCurrentSynchronizationContext());
         }
         watch.Stop();
         string tsOut = watch.Elapsed.ToString(@"m\:ss");
         lblTimeTaken.Text = "Time Elapsed : " + tsOut;
         lblStatus.Text    = "Image Encoded.";
         ImageOperations.DisplayImage(ImageMatrix, pictureBox2);
     }
     else
     {
         PasswordRegister register   = new PasswordRegister(txtInitialSeed.Text, TapPosition); // O(1)
         long             pixelsDone = 0;                                                      // UI
         Stopwatch        watch      = new Stopwatch();                                        //UI
         lblTimeTaken.Visible = true;                                                          //UI
         lblStatus.Text       = "Encoding Image...";
         watch.Start();                                                                        //UI
         for (int i = 0; i < ImageHeight; i++)
         {
             await Task.Run(() =>
             {
                 for (int j = 0; j < ImageWidth; j++)
                 {
                     ImageMatrix[i, j].red   ^= (byte)register.StepK(8);
                     ImageMatrix[i, j].green ^= (byte)register.StepK(8);
                     ImageMatrix[i, j].blue  ^= (byte)register.StepK(8);
                     pixelsDone++; // UI
                 }
             }).
             ContinueWith((ant) =>
             {
                 //lblStatus.Text = "Encoding " + pixelsDone + " pixels / " + (ImageHeight * ImageWidth) + " pixels : " + ((long)(pixelsDone * 100) / (ImageHeight * ImageWidth))
                 string te         = watch.Elapsed.ToString(@"m\:ss");
                 lblTimeTaken.Text = "Time Elapsed : " + te;
             }
                          , TaskScheduler.FromCurrentSynchronizationContext());
         }
         watch.Stop();
         string tsOut = watch.Elapsed.ToString(@"m\:ss");
         lblTimeTaken.Text = "Time Elapsed : " + tsOut;
         lblStatus.Text    = "Image Encoded.";
         ImageOperations.DisplayImage(ImageMatrix, pictureBox2);
     }
     //ImageColorFrequencies.GenerateFromImage(ImageMatrix);
 }
예제 #14
0
 public IActionResult OperateAlbum(AlbumFormModel model, IFormFile image)
 {
     if (ModelState.IsValid)
     {
         if (model.Id == 0 || model.Id == null)
         {
             try
             {
                 if (image != null)
                 {
                     string imageBase64Data = ImageOperations.GetBase64FromFile(image);
                     model.AlbumPhoto = imageBase64Data;
                     Album album = new Album()
                     {
                         AlbumPhoto = model.AlbumPhoto,
                         ColorId    = model.ColorId,
                         Name       = model.Name
                     };
                     db.Add(album);
                     db.SaveChanges();
                     return(StatusCode(200, "Eklendi"));
                 }
                 else
                 {
                     ModelState.AddModelError("error", "Lütfen Resim Ekleyin!");
                 }
             }
             catch (Exception)
             {
                 ModelState.AddModelError("error", "Error! An error occurred while album creating");
             }
         }
         else
         {
             var album = db.Album.Where(q => q.Id == model.Id).FirstOrDefault();
             if (album == null)
             {
                 ModelState.AddModelError("error", "Unknown Request!");
             }
             else
             {
                 if (image != null)
                 {
                     string imageBase64Data = ImageOperations.GetBase64FromFile(image);
                     album.AlbumPhoto = imageBase64Data;
                 }
                 album.Name    = model.Name;
                 album.ColorId = model.ColorId;
                 db.Update(album);
                 db.SaveChanges();
                 return(StatusCode(200, "Güncellendi!"));
             }
         }
     }
     return(BadRequest(new
     {
         Message = "Some error(s) occurred!",
         StatusCode = 400,
         ModelState = ModelState.ToList()
     }));
 }
        public async Task <IActionResult> NewOrderedItem([FromBody] OrderedItemViewModel model)
        {
            try
            {
                if (model == null)
                {
                    return(BadRequest("Error while recieving data"));
                }
                var userID = HttpContext.User.Identity.Name;
                if (userID == null)
                {
                    return(StatusCode(StatusCodes.Status401Unauthorized));
                }
                ApplicationUser user = await _Context.Set <ApplicationUser>().SingleOrDefaultAsync(x => x.UserName == userID);

                if (user == null)
                {
                    return(BadRequest("Token is not related to any Account"));
                }
                Account account = _Context.Set <Account>().Include(x => x.Cart)
                                  .ThenInclude(x => x.CartItems).FirstOrDefault(x => x.ID == user.AccountID);
                if (user == null || account == null)
                {
                    return(null);
                }

                OrderdItem Ordereditem = new OrderdItem()
                {
                    CreationDate = DateTime.Now,
                    NeededDate   = model.NeededDate,
                    Name         = model.Name,
                    Description  = model.Description,
                    AccountID    = account?.ID,
                };
                #region Save Other images
                if (model.Images != null && model.Images.Any(x => x.Length > 0))
                {
                    foreach (var file in model.Images.Where(x => x.Length > 0))
                    {
                        var itemImage = new OrderdItemImage()
                        {
                            OrderdItem = Ordereditem
                        };
                        itemImage.ImagePath = ImageOperations.SaveItemImage(file, itemImage);
                        if (!string.IsNullOrWhiteSpace(itemImage.ImagePath))
                        {
                            Ordereditem.OrderdItemImages.Add(itemImage);
                        }
                        else
                        {
                            itemImage.OrderdItem = null;
                        }
                    }
                }
                #endregion

                var data = _Context.Set <OrderdItem>().Add(Ordereditem);
                _Context.SaveChanges();
                return(Ok(Ordereditem.ID));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
예제 #16
0
        /// <summary>
        /// Compares two images based on defined set up.
        /// </summary>
        /// <returns>An instance of <see cref="ComparisonResult"/> that results of comparison.</returns>
        public ComparisonResult Compare()
        {
            if (_baselineImage == null)
            {
                throw new ArgumentNullException(nameof(_baselineImage), "Baseline image is required. Use CompareTo(...) method.");
            }

            if (_scaleToSameSize)
            {
                _actualImage = _resizer.Resize(_actualImage, _baselineImage.Width, _baselineImage.Height);
            }

            var comparisonAreaWidth = _actualImage.Width > _baselineImage.Width
                ? _actualImage.Width
                : _baselineImage.Width;

            var comparisonAreaHeight = _actualImage.Height > _baselineImage.Height
                ? _actualImage.Height
                : _baselineImage.Height;

            var comparisonResultImage = new Bitmap(comparisonAreaWidth, comparisonAreaHeight);

            var pixelMismatchCount = 0;

            var differenceBounds = new DifferenceBounds
            {
                Top    = comparisonAreaHeight,
                Left   = comparisonAreaWidth,
                Bottom = 0,
                Right  = 0
            };

            void updateBounds(int x, int y)
            {
                differenceBounds.Left   = Math.Min(x, differenceBounds.Left);
                differenceBounds.Right  = Math.Max(x, differenceBounds.Right);
                differenceBounds.Top    = Math.Min(y, differenceBounds.Top);
                differenceBounds.Bottom = Math.Max(y, differenceBounds.Bottom);
            }

            var startTime = DateTime.Now;

            var skipTheRest = false;

            for (var horizontalPosition = 0; horizontalPosition < comparisonAreaWidth; horizontalPosition++)
            {
                for (var verticalPosition = 0; verticalPosition < comparisonAreaHeight; verticalPosition++)
                {
                    if (skipTheRest ||
                        !IsPixelInBounds(_actualImage, horizontalPosition, verticalPosition) ||
                        !IsPixelInBounds(_baselineImage, horizontalPosition, verticalPosition))
                    {
                        break;
                    }

                    var actualPixel   = _actualImage.GetPixel(horizontalPosition, verticalPosition);
                    var expectedPixel = _baselineImage.GetPixel(horizontalPosition, verticalPosition);

                    var errorPixel = GetColorOfDifference(_settings.DifferenceType.Value)(actualPixel, expectedPixel);

                    var isPixelComparable = IsPixelComparable(expectedPixel, horizontalPosition, verticalPosition);

                    if (_ignoreColors)
                    {
                        if (IsPixelBrightnessSimilar(actualPixel, expectedPixel) || !isPixelComparable)
                        {
                            if (!_compareOnly && _settings.DifferenceType != DifferenceType.DiffOnly)
                            {
                                SetGrayScaledPixel(comparisonResultImage, expectedPixel, horizontalPosition, verticalPosition);
                            }
                        }
                        else
                        {
                            if (!_compareOnly)
                            {
                                comparisonResultImage.SetPixel(horizontalPosition, verticalPosition, errorPixel);
                            }

                            pixelMismatchCount++;
                            updateBounds(horizontalPosition, verticalPosition);
                        }
                        continue;
                    }

                    if (IsRGBSimilar(actualPixel, expectedPixel) || !isPixelComparable)
                    {
                        if (!_compareOnly && _settings.DifferenceType != DifferenceType.DiffOnly)
                        {
                            SetTransparentPixel(comparisonResultImage, actualPixel, horizontalPosition, verticalPosition);
                        }
                    }
                    else if (
                        _ignoreAntialiasing &&
                        (IsAntialiased(_actualImage, horizontalPosition, verticalPosition) ||
                         IsAntialiased(_baselineImage, horizontalPosition, verticalPosition))
                        )
                    {
                        if (IsPixelBrightnessSimilar(actualPixel, expectedPixel) || !isPixelComparable)
                        {
                            if (!_compareOnly && _settings.DifferenceType != DifferenceType.DiffOnly)
                            {
                                SetGrayScaledPixel(comparisonResultImage, expectedPixel, horizontalPosition, verticalPosition);
                            }
                        }
                        else
                        {
                            if (!_compareOnly)
                            {
                                comparisonResultImage.SetPixel(horizontalPosition, verticalPosition, errorPixel);
                            }

                            pixelMismatchCount++;
                            updateBounds(horizontalPosition, verticalPosition);
                        }
                    }
                    else
                    {
                        if (!_compareOnly)
                        {
                            comparisonResultImage.SetPixel(horizontalPosition, verticalPosition, errorPixel);
                        }

                        pixelMismatchCount++;
                        updateBounds(horizontalPosition, verticalPosition);
                    }

                    if (_compareOnly)
                    {
                        var currentMisMatchPercent = (double)pixelMismatchCount / (comparisonAreaHeight * comparisonAreaWidth) * 100;

                        if (currentMisMatchPercent > _returnEarlyThreshold)
                        {
                            skipTheRest = true;
                        }
                    }
                }
            }

            var rawMisMatchPercentage = (float)pixelMismatchCount / (comparisonAreaHeight * comparisonAreaWidth) * 100;

            return(new ComparisonResult
            {
                DiffBounds = differenceBounds,
                Mismatch = rawMisMatchPercentage,
                AnalysisTime = DateTime.Now - startTime,

                ImageDifference = !_compareOnly
                    ? ImageOperations.ConvertToBase64(comparisonResultImage)
                    : null,

                IsSameDimensions =
                    _actualImage.Width == _baselineImage.Width &&
                    _actualImage.Height == _baselineImage.Height,

                DimensionDifference = new DimensionDifference
                {
                    Width = _actualImage.Width - _baselineImage.Width,
                    Height = _actualImage.Height - _baselineImage.Height
                }
            });
        }
예제 #17
0
 private void MedianFilter(int maskSize)
 {
     ImageOperations.MedianFilter(SelectedImage.Bitmap, maskSize);
 }
예제 #18
0
 private void UpdateArtwork(string imagePath, byte[] imageData)
 {
     this.Artwork.SetValue(imagePath, imageData);
     this.ArtworkThumbnail = ImageOperations.PathToBitmapImage(imagePath, Convert.ToInt32(Constants.CoverLargeSize), Convert.ToInt32(Constants.CoverLargeSize));
     OnPropertyChanged(() => this.HasArtwork);
 }
예제 #19
0
 private void ChangeNegative()
 {
     ImageOperations.ChangeNegative(SelectedImage.Bitmap);
 }
예제 #20
0
        private void button3_Click(object sender, EventArgs e)
        {
            int    Tap  = Int32.Parse(textBox3.Text);
            string Seed = textBox1.Text;

            Program.tap_vedio      = Tap;
            Program.seed_len_vedio = Seed.Length;
            int seed = 0, Power = 1;
            int currunt = 0;

            for (int i = Seed.Length - 1; i > -1; i--)
            {
                if (Seed[i] == '1')
                {
                    seed += Power;
                }
                Power *= 2;
                if (currunt < 63)
                {
                    Program.seed1_vedio = seed;
                }
                if (currunt == 62)
                {
                    Power = 1;
                    seed  = 0;
                }
                if (currunt >= 63)
                {
                    Program.seed2_vedio = seed;
                }
                currunt++;
            }
            for (int i = 0; i < Program.index_vedio; i++)
            {
                string OpenedFilePath = Program.images_name[i];
                Program.OriginalImage = ImageOperations.OpenImage(OpenedFilePath + ".bmp");
                int Width, Height;
                Width  = ImageOperations.GetWidth(Program.OriginalImage);
                Height = ImageOperations.GetHeight(Program.OriginalImage);
                Program.ApplyEncryptionOrDecryption1();
            }

            VideoFileWriter writer = new VideoFileWriter();

            writer.Open(@"C:\Users\JOE\Desktop\Videos\mov2.avi", 320, 240, 25, VideoCodec.Default);

            // ... here you'll need to load your bitmaps
            for (int i = 0; i <= 1312; i++)
            {
                string s           = Convert.ToString(i);
                Bitmap original_bm = new Bitmap(@"C:\Users\JOE\Desktop\[TEMPLATE] ImageEncryptCompress\Put Pictures/" + s + ".bmp");
                writer.WriteVideoFrame(original_bm);
            }
            writer.Close();

            /* var size = new Size(1600, 1200);                    // The desired size of the video
             * var fps = 25;                                       // The desired frames-per-second
             * var codec = VideoCodec.MPEG4;                       // Which codec to use
             * var destinationfile = @"d:\myfile.avi";             // Output file
             * var srcdirectory = @"d:\foo\bar";                   // Directory to scan for images
             * var pattern = "*.jpg";                              // Files to look for in srcdirectory
             * var searchoption = SearchOption.TopDirectoryOnly;   // Search Top Directory Only or all subdirectories (recursively)?
             *
             * using (var writer = new VideoFileWriter())          // Initialize a VideoFileWriter
             * {
             *   writer.Open(destinationfile, size.Width, size.Height, fps, codec);              // Start output of video
             *   foreach (var file in Directory.GetFiles(srcdirectory, pattern, searchoption))   // Iterate files
             *   {
             *       using (var original = (Bitmap)Image.FromFile(file))     // Read bitmap
             *       using (var resized = new Bitmap(original, size))        // Resize if necessary
             *           writer.WriteVideoFrame(resized);                    // Write frame
             *   }
             *   writer.Close();                                 // Close VideoFileWriter
             * }      */
        }
예제 #21
0
 private void ChangeContrast(int contrastChange, ContrastType contrastType)
 {
     ImageOperations.ChangeContrast(SelectedImage.Bitmap, contrastChange, contrastType);
 }
예제 #22
0
        public async Task <IActionResult> AddNew([FromBody] ItemNewModel model)
        {
            try
            {
                if (model == null)
                {
                    return(BadRequest("Error while recieving data"));
                }
                var userID = HttpContext.User.Identity.Name;
                if (userID == null)
                {
                    return(StatusCode(StatusCodes.Status401Unauthorized));
                }
                ApplicationUser user = await _context.Set <ApplicationUser>().SingleOrDefaultAsync(x => x.UserName == userID);

                if (user == null)
                {
                    return(BadRequest("Token is not related to any Account"));
                }
                Account account = _context.Set <Account>().Include(x => x.Cart)
                                  .ThenInclude(x => x.CartItems).FirstOrDefault(x => x.ID == user.AccountID);
                if (user == null || account == null)
                {
                    return(null);
                }
                ItemCategory cat = _context.Set <ItemCategory>().FirstOrDefault(x => x.IsUsed == true);
                if (cat == null)
                {
                    return(StatusCode(StatusCodes.Status503ServiceUnavailable));
                }

                Item item = new Item()
                {
                    CashBack       = 0,
                    CreationDate   = DateTime.Now,
                    ItemCategoryID = cat.ID,
                    IsEnable       = true,

                    Price            = model.Price,
                    AccountID        = account.ID,
                    Name             = model.Name,
                    Quantity         = model.Quantity,
                    Description      = model.Description,
                    Owner            = model.Owner,
                    Mobile           = model.Mobile,
                    Location         = model.Location,
                    ShortDescription = model.Description.Substring(0, Math.Min(25, model.Description.Length))
                };
                #region Save Main Image
                if (model.Thumbnail != null && model.Thumbnail.Length > 0)
                {
                    item.ThumbnailImagePath = ImageOperations.SaveItemImage(model.Thumbnail, item);
                    var itemImage = new ItemImage()
                    {
                        Item = item
                    };
                    itemImage.ImagePath = ImageOperations.SaveItemImage(model.Thumbnail, itemImage);
                    if (!string.IsNullOrWhiteSpace(itemImage.ImagePath))
                    {
                        item.ItemImages.Add(itemImage);
                    }
                    else
                    {
                        itemImage.Item = null;
                    }
                }
                #endregion

                #region Save Other images
                if (model.Images != null && model.Images.Any(x => x.Length > 0))
                {
                    foreach (var file in model.Images.Where(x => x.Length > 0))
                    {
                        var itemImage = new ItemImage()
                        {
                            Item = item
                        };
                        itemImage.ImagePath = ImageOperations.SaveItemImage(file, itemImage);
                        if (!string.IsNullOrWhiteSpace(itemImage.ImagePath))
                        {
                            item.ItemImages.Add(itemImage);
                        }
                        else
                        {
                            itemImage.Item = null;
                        }
                    }
                }
                #endregion

                var data = _context.Set <Item>().Add(item);
                _context.SaveChanges();
                return(Ok(item.ID));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
예제 #23
0
 private void ChangeBrightness(int brightnessChange)
 {
     ImageOperations.ChangeBrightness(SelectedImage.Bitmap, brightnessChange);
 }
예제 #24
0
        public async Task <IActionResult> Add([FromBody] ADFullDataModel model)
        {
            #region Check user
            var userID = HttpContext.User.Identity.Name;
            if (userID == null)
            {
                return(StatusCode(StatusCodes.Status401Unauthorized));
            }
            ApplicationUser user = await _context.Set <ApplicationUser>().SingleOrDefaultAsync(item => item.UserName == userID);

            Account account = _context.Set <Account>()
                              .Include(x => x.ADs)
                              .FirstOrDefault(x => x.ID == user.AccountID);
            if (user == null || account == null)
            {
                return(null);
            }
            #endregion

            if (model == null || ModelState.IsValid == false)
            {
                return(BadRequest("Unvalid data model"));
            }

            try
            {
                #region Create new AD
                AD newAd = new AD()
                {
                    Name          = model.Name,
                    Title         = model.Title,
                    Description   = model.Description,
                    CategoryID    = model.CategoryID,
                    CreationDate  = DateTime.Now,
                    Radius        = 10,
                    Isapprove     = false,
                    ADViews       = 0,
                    NumberViews   = 0,
                    IsNegotiable  = model.IsNegotiable,
                    Email         = model.Email,
                    Phone         = model.Phone,
                    Longitude     = model.Longitude,
                    Latitude      = model.Latitude,
                    AccountID     = account.ID,
                    IsDisabled    = false,
                    Price         = (model.Price ?? 0) < 0 ? 0 : model.Price,
                    CurrencyID    = _context.Set <Currency>().FirstOrDefault(x => x.Code == model.CurrencyName)?.ID,
                    PriceType     = PriceType.Cash.ToString(),
                    ContactWay    = ContactWay.Both.ToString(),
                    PublishedDate = DateTime.Now
                };
                bool codeGenerated = await newAd.GenerateCode(_context);

                if (codeGenerated == false)
                {
                    return(BadRequest("Error in generate code"));
                }
                #endregion

                #region Ad category fields
                if (model.CategoryFieldOptions != null && model.CategoryFieldOptions.Count > 0)
                {
                    foreach (var item in model.CategoryFieldOptions)
                    {
                        var CatField = _context.Set <CategoryField>().Include(x => x.CategoryFieldOptions).SingleOrDefault(S => S.ID == item.CategoryFieldID);
                        CategoryFieldOption catOption = CatField.CategoryFieldOptions.FirstOrDefault(x => x.ID == item.CategoryFieldOptionID);
                        if (CatField == null)
                        {
                            continue;
                        }
                        newAd.ADExtraFields.Add(new AdExtraField
                        {
                            CategoryFieldOptionID = catOption?.ID,
                            Value = catOption?.Name ?? item.Value,
                            Name  = CatField.Name
                        });
                    }
                }
                #endregion

                #region Save Main Image
                if (model.MainImage != null && model.MainImage.Length > 0)
                {
                    string filename = ImageOperations.SaveImage(model.MainImage, newAd);
                    if (!string.IsNullOrWhiteSpace(filename))
                    {
                        newAd.ADImages.Add(new ADImage()
                        {
                            ImagePath = filename,
                            IsMain    = true
                        });
                    }
                }
                #endregion

                #region Save Other images
                if (model.Images != null && model.Images.Any(x => x.Length > 0))
                {
                    foreach (var file in model.Images.Where(x => x.Length > 0))
                    {
                        string filename = ImageOperations.SaveImage(file, newAd);
                        if (!string.IsNullOrWhiteSpace(filename))
                        {
                            newAd.ADImages.Add(new ADImage()
                            {
                                ImagePath = filename,
                                IsMain    = false
                            });
                        }
                    }
                }
                #endregion

                _context.Set <AD>().Add(newAd);
                await _context.SaveChangesAsync();

                return(Ok(newAd.Code));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
 private void BW_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     ProgressBar.Value = e.ProgressPercentage;
     ImageOperations.DisplayImage(SeamCarving.TempMatrix, ImageBox);
 }
 private void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     ImageOperations.DisplayImage(resizedImage, ImageBox);
 }
 private void mouseDown(object sender, MouseButtonEventArgs e)
 {
     mouseThread = new Thread(new ThreadStart(delegate() { getPixels(sender, e); }));
     ImageOperations.DisplayImage(ImageMatrix, ImageBox);
     mouseThread.Start();
 }
예제 #28
0
 public MainMenu()
 {
     InitializeComponent();
     imageOperations = new ImageOperations();
     CheckWorkingFoldersConfiguration();
 }
예제 #29
0
        public async Task <IActionResult> SendMessage([FromBody] MessageDataModel model)
        {
            #region Check user
            var userID = HttpContext.User.Identity.Name;
            if (userID == null)
            {
                return(StatusCode(StatusCodes.Status401Unauthorized));
            }
            ApplicationUser user = await _context.Set <ApplicationUser>().SingleOrDefaultAsync(item => item.UserName == userID);

            Account account = _context.Set <Account>()
                              .Include(x => x.Chats)
                              .ThenInclude(x => x.AD)
                              .ThenInclude(x => x.ADImages)
                              .Include(x => x.Chats)
                              .ThenInclude(x => x.Messages)
                              .FirstOrDefault(x => x.ID == user.AccountID);
            if (user == null || account == null)
            {
                return(null);
            }
            #endregion

            AD ad = _context.ADs.SingleOrDefault(x => x.ID == model.AdID);
            if (ad == null)
            {
                return(BadRequest("Ad not exist"));
            }
            try
            {
                var chat = _context.Chats.SingleOrDefault(x => x.ADID == model.AdID && x.OwnerAccountID == account.ID);
                if (chat == null)
                {
                    chat = new Chat()
                    {
                        ADID           = model.AdID,
                        Messages       = new System.Collections.ObjectModel.ObservableCollection <Message>(),
                        OwnerAccountID = account.ID,
                        OwnerName      = model.SenderName,
                        StartDate      = DateTime.UtcNow
                    };
                    _context.Chats.Add(chat);
                }
                Message message = new Message()
                {
                    Body              = model.Body,
                    Title             = model.Title,
                    SentDate          = DateTime.UtcNow,
                    SenderAccountID   = account.ID,
                    ReceiverAccountID = ad.AccountID,
                    SenderName        = model.SenderName,
                    Chat              = chat,
                    SeenDate          = null
                };
                if (model.Attachment != null || model.Attachment.Length > 0)
                {
                    string path = ImageOperations.SaveImage(model.Attachment, message);
                    message.FilePath = path;
                }

                _context.Messages.Add(message);
                await _context.SubmitAsync();

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
예제 #30
0
 public static Image Scale(this Image img, float scale, InterpolationMode filtering)
 {
     return(ImageOperations.Scale(img, scale, filtering));
 }
예제 #31
0
        // GET: api/Sensors/name
        public HttpResponseMessage Get(string sensorName, bool outputJSON)
        {
            var io                   = new ImageOperations();
            var sensorPath           = HttpContext.Current.Server.MapPath($"~/Sensors/{sensorName}");
            var sensorFileContent    = File.ReadAllText($"{sensorPath}/sensor.json");
            var js                   = new JavaScriptSerializer();
            var sensorDto            = js.Deserialize <SensorDto>(sensorFileContent);
            var parkingSpacesOutputs = new List <ParkingSpaceOutputDto>(sensorDto.ParkingSpaces.Length);


            var inputImage = sensorInputs.ContainsKey(sensorName)? sensorInputs[sensorName] : (Bitmap)Bitmap.FromFile($"{sensorPath}/{sensorDto.inputSample}");
            var emptyImage = (Bitmap)Bitmap.FromFile($"{sensorPath}/{sensorDto.EmptyImg}");

            var outputImage = (Bitmap)inputImage.Clone();

            using (Graphics outputGraphics = Graphics.FromImage(outputImage))
            {
                foreach (var parkingSpaceDto in sensorDto.ParkingSpaces)
                {
                    var inputCrop = (Bitmap)inputImage.Clone();
                    var emptyCrop = (Bitmap)emptyImage.Clone();

                    var sensorMask   = (Bitmap)Bitmap.FromFile($"{sensorPath}/{parkingSpaceDto.SensorMask}");
                    var locationMask = (Bitmap)Bitmap.FromFile($"{sensorPath}/{parkingSpaceDto.LocationMask}");

                    var sensorPixelCount = io.CountNonEmptyPixels(sensorMask);

                    io.CropImageWithMask(inputCrop, sensorMask);
                    io.CropImageWithMask(emptyCrop, sensorMask);
                    io.DiffImage(inputCrop, emptyCrop);
                    var  diffRGBSum = io.SumAllRGB(inputCrop);
                    bool vacant     = (diffRGBSum / sensorPixelCount) < parkingSpaceDto.Threshold;

                    if (vacant)
                    {
                        io.SetMaskColor(locationMask, 0, 255, 0);
                    }
                    else
                    {
                        io.SetMaskColor(locationMask, 255, 0, 0);
                    }
                    outputGraphics.DrawImage(locationMask, 0, 0, outputImage.Width, outputImage.Height);

                    parkingSpacesOutputs.Add(new ParkingSpaceOutputDto {
                        Name = parkingSpaceDto.Name, IsAvailable = vacant, ConfidenceLevel = ((float)diffRGBSum / sensorPixelCount / 255)
                    });
                }
            }
            if (outputJSON)
            {
                var outputDto = new SensorOutputDto {
                    ImageUrl = HttpContext.Current.Request.Url.OriginalString.Replace("outputJson=true", "outputJson=false"), ParkingSpaces = parkingSpacesOutputs.ToArray()
                };
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new StringContent(js.Serialize(outputDto).Replace(@"\u0026", "&")); // JavaScriptSerializer messes up &
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return(result);
            }
            else
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    outputImage.Save(ms, ImageFormat.Png);
                    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                    result.Content = new ByteArrayContent(ms.ToArray());
                    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                    return(result);
                }
            }
        }