private static string GetResizedImagePath(string filepath, int width, int height)
        {
            string resizedPath = filepath;

            if (width > 0 || height > 0)
            {
                resizedPath = filepath.GetPathForResizedImage(width, height);

                if (!Directory.Exists(resizedPath))
                    Directory.CreateDirectory(new FileInfo(resizedPath).DirectoryName);

                if (!File.Exists(resizedPath))
                {
                    var imageResizer = new ImageResizer(filepath);
                    if (width > 0 && height > 0)
                    {
                        imageResizer.Resize(width, height, ImageEncoding.Jpg90);
                    }
                    else if (width > 0)
                    {
                        imageResizer.Resize(width, ImageEncoding.Jpg90);
                    }
                    imageResizer.SaveToFile(resizedPath);
                    imageResizer.Dispose();
                }
            }
            return resizedPath;
        }
        public ActionResult Index(HttpPostedFileBase file)
        {
            var imageBytes = ReadFully(file.InputStream);
            var s3Client = new S3Client();
            var resizeSettings = new ResizeSettings
            {
                Settings = new List<ResizeSetting>
                {
                    new ResizeSetting
                    {
                        Name = "Large",
                        Width = 700,
                        ImageEncoding = ImageEncoding.Jpg90
                    },
                    new ResizeSetting
                    {
                        Name = "Small",
                        Width = 300,
                        ImageEncoding = ImageEncoding.Jpg90
                    },
                    new ResizeSetting
                    {
                        Name = "Thumb",
                        Width = 100,
                        Height = 100,
                        ImageEncoding = ImageEncoding.Jpg
                    }
                }
            };

            Parallel.ForEach(resizeSettings.Settings, resizeSetting =>
            {
                var imageResizer = new ImageResizer(imageBytes);
            
                string fileName = Path.GetFileNameWithoutExtension(file.FileName) + "_" + resizeSetting.Name + ".jpg";
                var resizedImage = resizeSetting.Height > 0
                    ? imageResizer.Resize(resizeSetting.Width, resizeSetting.Height, true, resizeSetting.ImageEncoding)
                    : imageResizer.Resize(resizeSetting.Width, resizeSetting.ImageEncoding);
                string result = s3Client.AddFile(fileName, new MemoryStream(resizedImage));
            });
            
            var vm = new AmazonViewModel
            {
                Filename = file.FileName,
                S3BaseUrl = Settings.Default.S3BaseUrl,
                CloudfrontBaseUrl = Settings.Default.CloudfrontBaseUrl,
                Bucket = Settings.Default.AWSPublicFilesBucket,
                ResizeSettings = resizeSettings
            };

            return View("Index", vm);
        }
Exemplo n.º 3
0
        public ActionResult Create([Bind(Include = "ProductID,Title,ShortDescription,Text,Price,ImageName,CreateDate")] Products products, List <int> selectedGroups, HttpPostedFileBase imageProduct, string tags)
        {
            if (ModelState.IsValid)
            {
                if (selectedGroups == null)
                {
                    ViewBag.ErrorSelectedGroup = true;
                    ViewBag.Groups             = db.Product_Groups.ToList();
                    return(View(products));
                }
                products.ImageName = "images.jpg";
                if (imageProduct != null && imageProduct.IsImage())
                {
                    products.ImageName = Guid.NewGuid().ToString() + Path.GetExtension(imageProduct.FileName);
                    imageProduct.SaveAs(Server.MapPath("/Images/ProductImages/" + products.ImageName));
                    ImageResizer img = new ImageResizer();
                    img.Resize(Server.MapPath("/Images/ProductImages/" + products.ImageName),
                               Server.MapPath("/Images/ProductImages/Thumb/" + products.ImageName));
                }
                products.CreateDate = DateTime.Now;
                db.Products.Add(products);

                foreach (int selectedGroup in selectedGroups)
                {
                    db.Prodct_Selected_Groups.Add(new Prodct_Selected_Groups()
                    {
                        ProductID = products.ProductID,
                        GroupID   = selectedGroup
                    });
                }

                if (!string.IsNullOrEmpty(tags))
                {
                    string[] tag = tags.Split(',');
                    foreach (string t in tag)
                    {
                        db.Product_Tags.Add(new Product_Tags()
                        {
                            ProductID = products.ProductID,
                            Tag       = t.Trim()
                        });
                    }
                }
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.Groups = db.Product_Groups.ToList();
            return(View(products));
        }
Exemplo n.º 4
0
        public ActionResult Edit(Article article, HttpPostedFileBase ArticleImage, string Tags)
        {
            if (ModelState.IsValid)
            {
                #region Upload Image
                if (ArticleImage != null)
                {
                    if (System.IO.File.Exists(Server.MapPath("/Files/ArticleImages/Image/" + article.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath("/Files/ArticleImages/Image/" + article.Image));
                    }

                    if (System.IO.File.Exists(Server.MapPath("/Files/ArticleImages/Thumb/" + article.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath("/Files/ArticleImages/Thumb/" + article.Image));
                    }

                    // Saving Temp Image
                    var newFileName = Guid.NewGuid() + Path.GetExtension(ArticleImage.FileName);
                    ArticleImage.SaveAs(Server.MapPath("/Files/ArticleImages/Temp/" + newFileName));
                    // Resize Image
                    ImageResizer image = new ImageResizer(820, 340, true);
                    image.Resize(Server.MapPath("/Files/ArticleImages/Temp/" + newFileName),
                                 Server.MapPath("/Files/ArticleImages/Image/" + newFileName));

                    ImageResizer thumb = new ImageResizer(400, 300, true);
                    thumb.Resize(Server.MapPath("/Files/ArticleImages/Temp/" + newFileName),
                                 Server.MapPath("/Files/ArticleImages/Thumb/" + newFileName));

                    // Deleting Temp Image
                    System.IO.File.Delete(Server.MapPath("/Files/ArticleImages/Temp/" + newFileName));

                    article.Image = newFileName;
                }
                #endregion

                _repo.Update(article);

                if (!string.IsNullOrEmpty(Tags))
                {
                    _repo.AddArticleTags(article.Id, Tags);
                }

                return(RedirectToAction("Index"));
            }
            ViewBag.Tags = Tags;
            ViewBag.ArticleCategoryId = new SelectList(_repo.GetArticleCategories(), "Id", "Title", article.ArticleCategoryId);
            return(View(article));
        }
        public ActionResult Edit([Bind(Include = "ProductID,UserID,ProductTypeId,Title,ShortDiscription,Text,PicThumbnail,KeyWord,Date,Vaziaat")] Product product, HttpPostedFileBase img)
        {
            if (ModelState.IsValid)
            {
                if (img != null && CheckContentImage.IsImage(img))
                {
                    if (!product.PicThumbnail.Contains("nopic"))
                    {
                        System.IO.File.Delete(Server.MapPath("/img/Products/") + product.PicThumbnail);
                        System.IO.File.Delete(Server.MapPath("/img/Products/1000×1500/") + product.PicThumbnail);
                        System.IO.File.Delete(Server.MapPath("/img/Products/192×288/") + product.PicThumbnail);
                        System.IO.File.Delete(Server.MapPath("/img/Products/262×393/") + product.PicThumbnail);
                        System.IO.File.Delete(Server.MapPath("/img/Products/thum/") + product.PicThumbnail);
                    }
                    string filename = Guid.NewGuid() + Path.GetExtension(img.FileName);
                    img.SaveAs(Server.MapPath("/img/Products/") + filename);
                    ImageResizer nrResizer = new ImageResizer();
                    nrResizer.Resize(Server.MapPath("/img/Products/") + filename,
                                     Server.MapPath("/img/Products/1000×1500/") + filename, 1000, 1500);
                    nrResizer.Resize(Server.MapPath("/img/Products/") + filename,
                                     Server.MapPath("/img/Products/192×288/") + filename, 192, 288);
                    nrResizer.Resize(Server.MapPath("/img/Products/") + filename,
                                     Server.MapPath("/img/Products/262×393/") + filename, 262, 393);
                    nrResizer.Resize(Server.MapPath("/img/Products/") + filename,
                                     Server.MapPath("/img/Products/thum/") + filename, 150, 150);

                    product.PicThumbnail = filename;
                }
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.ProductTypeId = new SelectList(db.ProductTypes, "ProductTypeId", "Title", product.ProductTypeId);
            ViewBag.UserID        = new SelectList(db.Userses, "UserID", "FullName", product.UserID);
            return(View(product));
        }
        public ActionResult Create([Bind(Include = "ProductID,UserID,ProductTypeId,Title,ShortDiscription,Text,PicThumbnail,KeyWord,Date,Vaziaat")] Product product, HttpPostedFileBase img)
        {
            if (ModelState.IsValid)
            {
                if (img != null && CheckContentImage.IsImage(img))
                {
                    string filename = Guid.NewGuid() + Path.GetExtension(img.FileName);
                    img.SaveAs(Server.MapPath("/img/Products/") + filename);
                    ImageResizer nrResizer = new ImageResizer();
                    nrResizer.Resize(Server.MapPath("/img/Products/") + filename,
                                     Server.MapPath("/img/Products/1000×1500/") + filename, 1000, 1500);
                    nrResizer.Resize(Server.MapPath("/img/Products/") + filename,
                                     Server.MapPath("/img/Products/192×288/") + filename, 192, 288);
                    nrResizer.Resize(Server.MapPath("/img/Products/") + filename,
                                     Server.MapPath("/img/Products/262×393/") + filename, 262, 393);
                    nrResizer.Resize(Server.MapPath("/img/Products/") + filename,
                                     Server.MapPath("/img/Products/thum/") + filename, 150, 150);

                    product.PicThumbnail = filename;
                }
                else
                {
                    product.PicThumbnail = "nopic.jpg";
                }

                product.UserID          = db.Userses.Where(p => p.UserName == User.Identity.Name).SingleOrDefault().UserID;
                product.Date            = DateTime.Now;
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.ProductTypeId = new SelectList(db.ProductTypes, "ProductTypeId", "Title", product.ProductTypeId);
            ViewBag.UserID        = new SelectList(db.Userses, "UserID", "FullName", product.UserID);
            return(View(product));
        }
Exemplo n.º 7
0
        public Thumbnail MakeThumbnail(string contentType, byte[] file, string fileName, int width)
        {
            var resized = _resizer.Resize(new Bitmap(new MemoryStream(file)), width);

            using (var output = new MemoryStream())
            {
                resized.Save(output, ImageFormat.Jpeg);
                return(new Thumbnail
                {
                    File = output.ToArray(),
                    ContentType = System.Net.Mime.MediaTypeNames.Image.Jpeg,
                    Name = Path.GetFileNameWithoutExtension(fileName) + ".jpg"
                });
            }
        }
Exemplo n.º 8
0
        public ActionResult GetFileThumbnail(string id, int width = 125)
        {
            var file = _repository.GetFile(id);

            if (file == null)
            {
                return(new HttpNotFoundResult());
            }

            var img    = _resizer.Resize(new Bitmap(new MemoryStream(file.Contents)), 125);
            var output = new MemoryStream();

            img.Save(output, System.Drawing.Imaging.ImageFormat.Jpeg);

            return(File(output.ToArray(), System.Net.Mime.MediaTypeNames.Image.Jpeg, file.FileName));
        }
Exemplo n.º 9
0
        private Tuple <List <YoloItem>, string, string, double> ProcessResizeBefore(YoloWrapper yoloWrapper, ImageResizer imageResize, byte[] imageData)
        {
            var sw = new Stopwatch();

            sw.Start();
            imageData = imageResize.Resize(imageData, 416, 416);
            sw.Stop();
            var resizeElapsed = sw.Elapsed.TotalMilliseconds;

            sw.Restart();
            var items = yoloWrapper.Detect(imageData).ToList();

            sw.Stop();

            return(new Tuple <List <YoloItem>, string, string, double>(items, $"{resizeElapsed:0.00}", $"{sw.Elapsed.TotalMilliseconds:0.00}", sw.Elapsed.TotalMilliseconds + resizeElapsed));
        }
Exemplo n.º 10
0
        public ActionResult Create([Bind(Include = "ProductID,ProductTitle,ShortDescription,Text,Price,ImageName")] Products products, List <int> SelectedGroups, HttpPostedFileBase imageProduct, string tags)
        {
            if (ModelState.IsValid)
            {
                if (SelectedGroups == null)
                {
                    ViewBag.NoSelectedgroup = "true";
                    ViewBag.Groups          = db.ProductGroupRepository.GetAll();
                    return(View(products));
                }
                products.ImageName = "no-image.png";
                if (imageProduct != null && imageProduct.IsImage())
                {
                    products.ImageName = Guid.NewGuid().ToString() + Path.GetExtension(imageProduct.FileName);
                    imageProduct.SaveAs(Server.MapPath("/Images/ProductImages/" + products.ImageName));
                    ImageResizer image = new ImageResizer();
                    image.Resize(Server.MapPath("/Images/ProductImages/" + products.ImageName), Server.MapPath("/Images/ProductImages/Thumb/" + products.ImageName));
                }
                products.CreateDate = DateTime.Now;
                db.ProductRepository.Insert(products);
                foreach (int selectedGroup in SelectedGroups)
                {
                    db.SelectedGroupRepository.Insert(new SelectedProductGroup()
                    {
                        ProductID = products.ProductID,
                        GroupID   = selectedGroup
                    });
                }
                if (!string.IsNullOrEmpty(tags))
                {
                    string[] Tags = tags.Split('،');
                    foreach (string tag in Tags)
                    {
                        db.TagsRepository.Insert(new Tags()
                        {
                            ProductID = products.ProductID,
                            Tag       = tag.Trim()
                        });
                    }
                }
                db.Save();

                return(RedirectToAction("Index"));
            }
            ViewBag.Groups = db.ProductGroupRepository.GetAll();
            return(View(products));
        }
Exemplo n.º 11
0
        public void TestResize()
        {
            const int    scaleFactor = 4;
            ImageResizer resizer     = new ImageResizer();

            ImageInfo info = resizer.GetInfo(TestImage);

            int expectedWidth  = info.Width / scaleFactor;
            int expectedHeight = info.Height / scaleFactor;

            resizer.Resize(TestImage, DestinationImage, expectedWidth, expectedHeight);

            ImageInfo resizedInfo = resizer.GetInfo(DestinationImage);

            Assert.AreEqual(expectedWidth, resizedInfo.Width);
            Assert.AreEqual(expectedHeight, resizedInfo.Height);
        }
Exemplo n.º 12
0
        public ActionResult Create(Article article, HttpPostedFileBase ArticleImage, string Tags)
        {
            if (ModelState.IsValid)
            {
                if (!HttpContext.User.Identity.IsAuthenticated)
                {
                    ViewBag.Message = "کاربر وارد کننده پیدا نشد.";
                    return(View(article));
                }


                #region Upload Image
                if (ArticleImage != null)
                {
                    // Saving Temp Image
                    var newFileName = Guid.NewGuid() + Path.GetExtension(ArticleImage.FileName);
                    ArticleImage.SaveAs(Server.MapPath("/Files/ArticleImages/Temp/" + newFileName));
                    // Resize Image
                    ImageResizer image = new ImageResizer(850, 400, true);
                    image.Resize(Server.MapPath("/Files/ArticleImages/Temp/" + newFileName),
                                 Server.MapPath("/Files/ArticleImages/Image/" + newFileName));

                    ImageResizer thumb = new ImageResizer(200, 200, true);
                    thumb.Resize(Server.MapPath("/Files/ArticleImages/Temp/" + newFileName),
                                 Server.MapPath("/Files/ArticleImages/Thumb/" + newFileName));

                    // Deleting Temp Image
                    System.IO.File.Delete(Server.MapPath("/Files/ArticleImages/Temp/" + newFileName));

                    article.Image = newFileName;
                }
                #endregion

                _repo.AddArticle(article);

                if (!string.IsNullOrEmpty(Tags))
                {
                    _repo.AddArticleTags(article.Id, Tags);
                }

                return(RedirectToAction("Index"));
            }
            ViewBag.Tags = Tags;
            ViewBag.ArticleCategoryId = new SelectList(_repo.GetArticleCategories(), "Id", "Title", article.ArticleCategoryId);
            return(View(article));
        }
Exemplo n.º 13
0
 public ActionResult Gallery(Product_Galleries galleries, HttpPostedFileBase imgUp)
 {
     if (ModelState.IsValid)
     {
         if (imgUp != null && imgUp.IsImage())
         {
             galleries.ImageName = Guid.NewGuid().ToString() + Path.GetExtension(imgUp.FileName);
             imgUp.SaveAs(Server.MapPath("/Images/ProductImages/" + galleries.ImageName));
             ImageResizer img = new ImageResizer();
             img.Resize(Server.MapPath("/Images/ProductImages/" + galleries.ImageName),
                        Server.MapPath("/Images/ProductImages/Thumb/" + galleries.ImageName));
             db.Product_Galleries.Add(galleries);
             db.SaveChanges();
         }
     }
     return(RedirectToAction("Gallery", new { id = galleries.ProductID }));
 }
Exemplo n.º 14
0
        public virtual void CreateSize(Url virtualPath, byte[] image, ImageSizeElement size)
        {
            if (!size.ResizeOnUpload)
            {
                return;
            }

            string resizedPath = ImagesUtility.GetResizedPath(virtualPath, size.Name);

            using (var sourceStream = new MemoryStream(image))
            {
                if (size.Width <= 0 && size.Height <= 0)
                {
                    using (var destinationStream = files.OpenFile(resizedPath))
                    {
                        int b;
                        while ((b = sourceStream.ReadByte()) != -1)
                        {
                            destinationStream.WriteByte((byte)b);
                        }
                    }
                }
                else
                {
                    if (!files.FileExists(resizedPath) || size.Replace)
                    {
                        // Delete the image before writing.
                        // Fixes a weird bug where overwriting the original file while it still exists
                        //  leaves the resized image the with the exact same file size as the original even
                        //  though it should be smaller.
                        if (files.FileExists(resizedPath))
                        {
                            files.DeleteFile(resizedPath);
                        }

                        using (var destinationStream = files.OpenFile(resizedPath))
                        {
                            resizer.Resize(sourceStream, new ImageResizeParameters(size.Width, size.Height, size.Mode)
                            {
                                Quality = size.Quality
                            }, destinationStream);
                        }
                    }
                }
            }
        }
        public ActionResult Edit(GalleryVideo gallery, HttpPostedFileBase GalleryVideo, HttpPostedFileBase GalleryImage)
        {
            if (ModelState.IsValid)
            {
                #region Upload Video
                if (GalleryVideo != null)
                {
                    if (System.IO.File.Exists(Server.MapPath("/Files/GalleryVideos/" + gallery.Video)))
                    {
                        System.IO.File.Delete(Server.MapPath("/Files/GalleryVideos/" + gallery.Video));
                    }

                    var newFileName = Guid.NewGuid() + Path.GetExtension(GalleryVideo.FileName);
                    GalleryVideo.SaveAs(Server.MapPath("/Files/GalleryVideos/" + newFileName));
                    gallery.Video = newFileName;
                }
                #endregion
                #region Upload Image
                if (GalleryImage != null)
                {
                    if (System.IO.File.Exists(Server.MapPath("/Files/GalleryImages/" + gallery.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath("/Files/GalleryImages/" + gallery.Image));
                    }

                    // Saving Temp Image
                    var newFileName = Guid.NewGuid() + Path.GetExtension(GalleryImage.FileName);
                    GalleryImage.SaveAs(Server.MapPath("/Files/GalleryImages/Temp/" + newFileName));

                    // Resizing Image
                    ImageResizer imageCut = new ImageResizer(1200, 1200, true);

                    imageCut.Resize(Server.MapPath("/Files/GalleryImages/Temp/" + newFileName),
                                    Server.MapPath("/Files/GalleryImages/" + newFileName));

                    // Deleting Temp Image
                    System.IO.File.Delete(Server.MapPath("/Files/GalleryImages/Temp/" + newFileName));
                    gallery.Image = newFileName;
                }
                #endregion
                _repo.Update(gallery);
                return(RedirectToAction("Index"));
            }
            return(View(gallery));
        }
Exemplo n.º 16
0
        public ActionResult Create([Bind(Include = "ProductID,ProductGroupID,ProductSubGroupID,ProductTitle,ProductShortText,ProductText,ProductImage,ProductIsFavourite,ProductDateCreate")] Product product, HttpPostedFileBase imgProduct)
        {
            if (ModelState.IsValid)
            {
                product.ProductImage      = "";
                product.ProductDateCreate = DateTime.Now;
                if (imgProduct != null && imgProduct.IsImage())
                {
                    string mainImagePath  = "/Images/ProductImages/MainImage/";
                    string thumbImagePath = "/Images/ProductImages/ThumbImage/";

                    if (!Directory.Exists(thumbImagePath))
                    {
                        Directory.CreateDirectory(Server.MapPath(thumbImagePath));
                    }

                    if (!Directory.Exists(mainImagePath))
                    {
                        Directory.CreateDirectory(Server.MapPath(mainImagePath));
                    }

                    string imageName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(imgProduct.FileName);
                    product.ProductImage = imageName;
                    imgProduct.SaveAs(Server.MapPath(mainImagePath + imageName));

                    ImageResizer img = new ImageResizer();
                    img.Resize(Server.MapPath(mainImagePath + imageName),
                               Server.MapPath(thumbImagePath + imageName));

                    db.Products.Add(product);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
                else
                {
                    ModelState.AddModelError("ProductImage", "تصویر را انتخاب کنید!");
                    return(View(product));
                }
            }

            ViewBag.ProductGroupID    = new SelectList(db.ProductGroups, "ProductGroupID", "ProductGroupTitle", product.ProductGroupID);
            ViewBag.ProductSubGroupID = new SelectList(db.ProductGroups, "ProductGroupID", "ProductGroupTitle", product.ProductSubGroupID);
            return(View(product));
        }
Exemplo n.º 17
0
        public ActionResult Gallery(ProductGallery productGallery, HttpPostedFileBase imgUpdate)
        {
            //if (ModelState.IsValid)
            //{
            if (imgUpdate != null && imgUpdate.IsImage())
            {
                productGallery.ImageName = Guid.NewGuid().ToString() + Path.GetExtension(imgUpdate.FileName);
                imgUpdate.SaveAs(Server.MapPath("~/Content/img/Product/" + productGallery.ImageName));
                ImageResizer img = new ImageResizer();
                img.Resize(Server.MapPath("~/Content/img/Product/" + productGallery.ImageName),
                           Server.MapPath("~/Content/img/Product/Thumb/" + productGallery.ImageName));

                context.ProductGalleryRepository.Insert(productGallery);
                context.Save();
            }
            //}
            //ViewBag.Galleries = context.ProductGalleryRepository.Get(g => g.ProductId == id);
            return(RedirectToAction("Gallery", new { id = productGallery.ProductId }));
        }
Exemplo n.º 18
0
        public ActionResult Edit(Service service, HttpPostedFileBase ServiceImage, HttpPostedFileBase ServiceFile)
        {
            if (ModelState.IsValid)
            {
                #region Upload Image
                if (ServiceImage != null)
                {
                    if (System.IO.File.Exists(Server.MapPath("/Files/Services/Image/" + service.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath("/Files/Services/Image/" + service.Image));
                    }

                    if (System.IO.File.Exists(Server.MapPath("/Files/Services/Thumb/" + service.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath("/Files/Services/Thumb/" + service.Image));
                    }

                    var newFileName = Guid.NewGuid() + Path.GetExtension(ServiceImage.FileName);
                    ServiceImage.SaveAs(Server.MapPath("/Files/Services/Image/" + newFileName));

                    ImageResizer thumb = new ImageResizer();
                    thumb.Resize(Server.MapPath("/Files/Services/Image/" + newFileName), Server.MapPath("/Files/Services/Thumb/" + newFileName));
                    service.Image = newFileName;
                }
                #endregion
                #region Upload File
                if (ServiceFile != null)
                {
                    if (System.IO.File.Exists(Server.MapPath("/Files/Services/File/" + service.File)))
                    {
                        System.IO.File.Delete(Server.MapPath("/Files/Services/File/" + service.File));
                    }

                    var newFileName = Guid.NewGuid() + Path.GetExtension(ServiceFile.FileName);
                    ServiceFile.SaveAs(Server.MapPath("/Files/Services/File/" + newFileName));
                    service.File = newFileName;
                }
                #endregion
                _repo.Update(service);
                return(RedirectToAction("Index"));
            }
            return(View(service));
        }
Exemplo n.º 19
0
        //[Route("ProductGalleries/Index/{id}")]
        public ActionResult Create([Bind(Include = "ProductGalleryID,ProductID,ProductColor,ProductImageName,ProductImageTitle")] ProductGallery productGallery, int id, HttpPostedFileBase imgProductGallery)
        {
            productGallery.ProductID = id;
            if (ModelState.IsValid)
            {
                if (imgProductGallery != null && imgProductGallery.IsImage())
                {
                    string mainImagePath  = "/Images/ProductGallery/MainImage/";
                    string thumbImagePath = "/Images/ProductGallery/ThumbImage/";

                    if (!Directory.Exists(thumbImagePath))
                    {
                        Directory.CreateDirectory(Server.MapPath(thumbImagePath));
                    }

                    if (!Directory.Exists(mainImagePath))
                    {
                        Directory.CreateDirectory(Server.MapPath(mainImagePath));
                    }

                    string imageName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(imgProductGallery.FileName);
                    productGallery.ProductImageName = imageName;
                    imgProductGallery.SaveAs(Server.MapPath(mainImagePath + imageName));

                    ImageResizer img = new ImageResizer();
                    img.Resize(Server.MapPath(mainImagePath + imageName),
                               Server.MapPath(thumbImagePath + imageName));

                    db.ProductGalleries.Add(productGallery);
                    db.SaveChanges();
                    return(RedirectToAction("Create"));
                    //return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError("ProductImageName", "تصویر را انتخاب کنید!");
                    return(View(productGallery));
                }
            }

            ViewBag.ProductID = new SelectList(db.Products, "ProductID", "ProductTitle", productGallery.ProductID);
            return(View(productGallery));
        }
Exemplo n.º 20
0
        public ActionResult Edit(Project project, HttpPostedFileBase ProjectImage)
        {
            if (ModelState.IsValid)
            {
                #region Upload Image
                if (ProjectImage != null)
                {
                    if (System.IO.File.Exists(Server.MapPath("/Files/ProjectImages/Image/" + project.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath("/Files/ProjectImages/Image/" + project.Image));
                    }

                    if (System.IO.File.Exists(Server.MapPath("/Files/ProjectImages/Thumb/" + project.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath("/Files/ProjectImages/Thumb/" + project.Image));
                    }

                    // Saving Temp Image
                    var newFileName = Guid.NewGuid() + Path.GetExtension(ProjectImage.FileName);
                    ProjectImage.SaveAs(Server.MapPath("/Files/ProjectImages/Temp/" + newFileName));
                    // Resize Image
                    ImageResizer image = new ImageResizer(840, 385, true);
                    image.Resize(Server.MapPath("/Files/ProjectImages/Temp/" + newFileName),
                                 Server.MapPath("/Files/ProjectImages/Image/" + newFileName));

                    ImageResizer thumb = new ImageResizer(370, 250, true);
                    thumb.Resize(Server.MapPath("/Files/ProjectImages/Temp/" + newFileName),
                                 Server.MapPath("/Files/ProjectImages/Thumb/" + newFileName));

                    // Deleting Temp Image
                    System.IO.File.Delete(Server.MapPath("/Files/ProjectImages/Temp/" + newFileName));

                    project.Image = newFileName;
                }
                #endregion

                _repo.Update(project);
                return(RedirectToAction("Index"));
            }
            ViewBag.ProjectTypeId = new SelectList(_repo.GetProjectTypes(), "Id", "Title", project.ProjectTypeId);
            return(View(project));
        }
Exemplo n.º 21
0
        public ActionResult Gallery(Gallery gallery, HttpPostedFileBase imgUp)
        {
            if (ModelState.IsValid)
            {
                if (imgUp != null && imgUp.IsImage())
                {
                    gallery.ImageName = Guid.NewGuid().ToString() + Path.GetExtension(imgUp.FileName);
                    imgUp.SaveAs(Server.MapPath("/Content/Image/Product/" + gallery.ImageName));
                    ImageResizer imgResizer = new ImageResizer();
                    imgResizer.Resize(Server.MapPath("/Content/Image/Product/" + gallery.ImageName),
                                      Server.MapPath("/Content/Image/Product/Thumbnail/" + gallery.ImageName));

                    _galleryBusiness.Insert(gallery);
                    _galleryBusiness.Save();
                    return(RedirectToAction("Gallery", new { id = gallery.ProductId }));
                }
            }

            return(RedirectToAction("Gallery", new { id = gallery.ProductId }));
        }
Exemplo n.º 22
0
        public ActionResult Gallery(ProductGallery productGallery, HttpPostedFileBase imgUp)
        {
            if (ModelState.IsValid)
            {
                if (imgUp != null && imgUp.IsImage())
                {
                    productGallery.Image = Guid.NewGuid().ToString() + Path.GetExtension(imgUp.FileName);
                    imgUp.SaveAs(Server.MapPath("/img/Products/" + productGallery.Image));
                    ImageResizer img = new ImageResizer();

                    img.Resize(Server.MapPath("/img/Products/" + productGallery.Image),
                               Server.MapPath("/img/Products/1000×1500/" + productGallery.Image), 1000, 1500);

                    db.ProductGalleries.Add(productGallery);
                    db.SaveChanges();
                }
            }

            return(RedirectToAction("Gallery", new { id = productGallery.ProductID }));
        }
        public void Resize()
        {
            //Assign
            var currentPath  = Directory.GetCurrentDirectory();
            var source       = $"{currentPath}\\Image\\TestFiles\\smile.bmp";
            var target       = $"{currentPath}\\Image\\TestFiles\\Result_resized.bmp";
            var imageResizer = new ImageResizer();

            //Act
            imageResizer.Resize(source, target, 50, 50);

            //Assert
            File.Exists(target).Should().BeTrue();

            using (var img = System.Drawing.Image.FromFile(target))
            {
                img.Height.Should().Be(50);
                img.Width.Should().Be(31);
            }
        }
 public void SmallImagesAreNotScaledDown()
 {
     foreach (uint offset in new[] { 0, 10, 1000 })
     {
         foreach (var sourceFile in Directory.GetFiles(TestdataDirectory, "*.jpg"))
         {
             var targetFile = Path.GetFileNameWithoutExtension(sourceFile) + "_s.jpg";
             using (var sourceImage = Image.FromFile(sourceFile))
             {
                 var targetMaxSize = (uint)Math.Max(sourceImage.Size.Height, sourceImage.Size.Width) + offset;
                 var resizer       = new ImageResizer(75, 0.80f);
                 resizer.Resize(sourceFile, targetFile, targetMaxSize);
                 using (var targetImage = Image.FromFile(targetFile))
                 {
                     Assert.AreEqual(targetImage.Size, sourceImage.Size);
                 }
             }
         }
     }
 }
 public void SmallImagesAreNotScaledDown()
 {
     foreach (uint offset in new[] { 0, 10, 1000 })
     {
         foreach (var sourceFile in Directory.GetFiles(TestdataDirectory, "*.jpg"))
         {
             var targetFile = Path.GetFileNameWithoutExtension(sourceFile) + "_s.jpg";
             using (var sourceImage = Image.FromFile(sourceFile))
             {
                 var targetMaxSize = (uint)Math.Max(sourceImage.Size.Height, sourceImage.Size.Width) + offset;
                 var resizer = new ImageResizer(75, 0.80f);
                 resizer.Resize(sourceFile, targetFile, targetMaxSize);
                 using (var targetImage = Image.FromFile(targetFile))
                 {
                     Assert.AreEqual(targetImage.Size, sourceImage.Size);
                 }
             }
         }
     }
 }
Exemplo n.º 26
0
        public bool UploadImage(int id, HttpPostedFileBase File)
        {
            #region Upload Image
            if (File != null)
            {
                var product = _repo.Get(id);
                if (product.Image != null)
                {
                    if (System.IO.File.Exists(Server.MapPath("/Files/ProductGroupImages/Image/" + product.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath("/Files/ProductGroupImages/Image/" + product.Image));
                    }

                    if (System.IO.File.Exists(Server.MapPath("/Files/ProductGroupImages/Thumb/" + product.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath("/Files/ProductImages/Thumb/" + product.Image));
                    }
                }
                // Saving Temp Image
                var newFileName = Guid.NewGuid() + Path.GetExtension(File.FileName);
                File.SaveAs(Server.MapPath("/Files/ProductImages/Temp/" + newFileName));
                // Resize Image
                ImageResizer image = new ImageResizer(850, 400, true);
                image.Resize(Server.MapPath("/Files/ProductImages/Temp/" + newFileName),
                             Server.MapPath("/Files/ProductImages/Image/" + newFileName));

                ImageResizer thumb = new ImageResizer(200, 200, true);
                thumb.Resize(Server.MapPath("/Files/ProductImages/Temp/" + newFileName),
                             Server.MapPath("/Files/ProductImages/Thumb/" + newFileName));

                // Deleting Temp Image
                System.IO.File.Delete(Server.MapPath("/Files/ProductImages/Temp/" + newFileName));
                product.Image = newFileName;
                _repo.Update(product);
                return(true);
            }
            #endregion

            return(false);
        }
        public async Task <ActionResult> Create(Article article, HttpPostedFileBase imageProduct, HttpPostedFileBase videoProduct)
        {
            if (ModelState.IsValid)
            {
                article.Image = "images.jpg";
                if (imageProduct != null && imageProduct.IsImage())
                {
                    article.Image = Guid.NewGuid().ToString() + Path.GetExtension(imageProduct.FileName);
                    imageProduct.SaveAs(Server.MapPath("/Images/Articles/" + article.Image));
                    ImageResizer img = new ImageResizer();
                    img.Resize(Server.MapPath("/Images/Articles/" + article.Image),
                               Server.MapPath("/Images/Articles/Thumb/" + article.Image));
                }

                if (videoProduct != null)
                {
                    article.Video = Guid.NewGuid().ToString() + Path.GetExtension(videoProduct.FileName);
                    videoProduct.SaveAs(Server.MapPath("/Videos/" + article.Video));
                }



                article.CreateDate = DateTime.Now;
                article.Author     = "ایمان صفری";

                db.ArticleRepository.AddNew(article);
                db.Save();
                return(RedirectToAction("Index"));
            }
            List <SelectListItem> groupList = new List <SelectListItem>();

            foreach (var group in db.ArticleGroupRepository.GetAll().Result)
            {
                groupList.Add(new SelectListItem {
                    Text = group.GroupName, Value = group.ID.ToString()
                });
            }
            ViewBag.articlegroup = groupList;
            return(View(article));
        }
Exemplo n.º 28
0
        private void BrowseForFile_Btn_Click(object sender, EventArgs e)
        {
            if (BrowseImageDialog.ShowDialog() == DialogResult.OK)
            {
                if (EditedImage_Picturebox.Image != null)
                {
                    EditedImage_Picturebox.Image = null;
                }

                var fileSize = fileHandler.GetFileSizeInMegaBytes(BrowseImageDialog.FileName);

                if (fileSize > 3)
                {
                    DialogResult result = MessageBox.Show("The image selected is larger than 3 megabyte. Actual Image size is " + ((decimal)fileSize).ToString("N2") + " megabytes." +
                                                          "\nImage processing will be gradually slower the larger the file is." +
                                                          "\nDo you wish to proceed anyways?", "File Size Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (result == DialogResult.Yes)
                    {
                    }
                    else
                    {
                        OriginalImage_Picturebox.Image = null;
                        return;
                    }
                }

                Bitmap originalImage = (Bitmap)Bitmap.FromFile(BrowseImageDialog.FileName);
                Bitmap resizedImage  = ImageResizer.Resize(originalImage, OriginalImage_Picturebox.Width, OriginalImage_Picturebox.Height);
                OriginalImage_Picturebox.Image = resizedImage;
                imageModifier.OriginalImage    = originalImage;
                originalFileName = BrowseImageDialog.SafeFileName;

                indexOfDotInFilePath = originalFileName.IndexOf('.');

                Greyscale_Btn.Enabled = true;
                Negative_Btn.Enabled  = true;
                Blur_Btn.Enabled      = true;
            }
        }
Exemplo n.º 29
0
        //private string _source;

        public ViewImageViewModel(INavigation navigation, string path)
        {
            Navigation = navigation;
            Title      = "Image Viewer";

            var streamReader = new StreamReader(path);

            var bytes = default(byte[]);

            var memstream = new MemoryStream();

            streamReader.BaseStream.CopyTo(memstream);
            bytes = memstream.ToArray();

            var resizeBytes = ImageResizer.Resize(bytes, 0.75);

            Source = ImageSource.FromStream(() => new MemoryStream(resizeBytes));
            Path   = path;

            //_source = image.Source.ToString().Substring(6);
            //"/storage/emulated/0/Android/data/co.uk.ivNet.DiGiT/files/Pictures/temp/IMG-20180128-WA0000.jpg";
        }
Exemplo n.º 30
0
        /// <summary>
        /// accept file from content question in src img tag. Move file from srcFolder to destFolder
        /// </summary>
        /// <param name="content">Content Question with html code</param>
        /// <param name="srcFolder">folder include image file</param>
        /// <param name="destFolder">folder save image file</param>
        /// <param name="w">with image when resize</param>
        /// <param name="h">height image when resize</param>
        /// <param name="encoding">image encoding</param>
        private void AcceptFile(string content, string srcFolder, string destFolder, int w, int h, ImageEncoding encoding)
        {
            try
            {
                if (w <= 0 || h <= 0)
                {
                    AcceptFile(content, srcFolder, destFolder);
                }

                if (!Directory.Exists(srcFolder))
                {
                    throw new FileNotFoundException("Thu m?c ch?a ?nh không t?n t?i", srcFolder);
                }
                if (!Directory.Exists(destFolder))
                {
                    Directory.CreateDirectory(destFolder);
                }
                var files = GetFileName(content);

                foreach (var fileName in files)
                {
                    if (System.IO.File.Exists(srcFolder + fileName))
                    {
                        if (System.IO.File.Exists(destFolder + fileName))
                        {
                            System.IO.File.Delete(destFolder + fileName);
                        }
                        System.IO.File.Copy(srcFolder + fileName, destFolder + fileName);
                        var resize = new ImageResizer(destFolder + fileName);
                        resize.Resize(w, h, encoding);
                        resize.SaveToFile(destFolder + fileName);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 31
0
        public ActionResult Edit([Bind(Include = "NewsId,Title,Description,Text,ImageName,Visit,CreateDate")] News news, HttpPostedFileBase imgUp)
        {
            if (ModelState.IsValid)
            {
                if (imgUp != null && imgUp.IsImage())
                {
                    System.IO.File.Delete(Server.MapPath("/Content/Image/News/" + news.ImageName));
                    System.IO.File.Delete(Server.MapPath("/Content/Image/News/Thumbnail/" + news.ImageName));

                    news.ImageName = Guid.NewGuid().ToString() + Path.GetExtension(imgUp.FileName);
                    imgUp.SaveAs(Server.MapPath("/Content/Image/News/" + news.ImageName));
                    ImageResizer imageResizer = new ImageResizer();
                    imageResizer.Resize(Server.MapPath("/Content/Image/News/" + news.ImageName),
                                        Server.MapPath("/Content/Image/News/Thumbnail/" + news.ImageName));
                }
                _newsBusiness.Update(news);
                _newsBusiness.Save();
                return(RedirectToAction("Index"));
            }

            return(View(news));
        }
Exemplo n.º 32
0
        /// <summary>
        /// The method for handling upload a file to server
        /// </summary>
        /// <param name="file">
        /// The file will be uploaded to server
        /// </param>
        /// <param name="maximumWidth">
        /// Maximum width
        /// </param>
        /// <param name="storagePath">
        /// The directory which the file will be stored in
        /// </param>
        /// <param name="fileName">
        /// fileName will be created based on DateTime.Now
        /// as binary string and uploaded file extension
        /// </param>
        public static bool UploadAndResizeFile(HttpPostedFile file, int maximumWidth,
                                               string storagePath, ref string fileName)
        {
            var result = true;

            try
            {
                // Get storage upload path
                var fileInfo = new FileInfo(file.FileName);
                fileName = DateTime.Now.ToBinary() + fileInfo.Extension;
                var fullStoragePath = Path.Combine(storagePath, fileName);

                // Get to be uploaded image width
                using (Image sourceImage = Image.FromStream(file.InputStream))
                {
                    var uploadImageWidth = sourceImage.Width;

                    if (uploadImageWidth > maximumWidth)
                    {
                        var fileByteArray = ConvertImageToByteArray(sourceImage, fileInfo.Extension);
                        var imageResizer  = new ImageResizer(fileByteArray);
                        imageResizer.Resize(maximumWidth, ImageEncoding.Jpg90);
                        imageResizer.SaveToFile(fullStoragePath);
                        imageResizer.Dispose();
                    }
                    else
                    {
                        file.SaveAs(fullStoragePath);
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;
                Logger.ErrorFormat("UploadAndResizeFile: {0}", ex.ToString());
            }
            return(result);
        }
Exemplo n.º 33
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest request,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var formData = await request.ReadFormAsync();

            var requestModel = ProcessImageRequest.ParseFrom(formData);

            log.LogInformation($"Request data: {requestModel}");

            var errors = requestModel.Validate();

            if (errors.Any())
            {
                log.LogWarning($"Rejecting request with validation errors: {string.Join(" ", errors)}");
                return(new BadRequestObjectResult(errors));
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            using (var sourceImage = Image.Load(requestModel.Image.OpenReadStream()))
            {
                if (requestModel.Resize || requestModel.Image.Length > maxFileSizeInBytesBeforeResizing)
                {
                    log.LogInformation($"Resizing image per request or because it is too large.");
                    resizer.Resize(sourceImage, GameBoyConstants.ScreenWidth, GameBoyConstants.ScreenHeight);
                }
                using (var outputImage = converter.Convert(sourceImage, requestModel.Palette))
                {
                    stopwatch.Stop();
                    log.LogInformation($"Processed image in {stopwatch.Elapsed.TotalSeconds:n3} sec.");
                    return(new FileContentResult(converter.ToBytes(outputImage), "image/png"));
                }
            }
        }
        public void Thumbails()
        {
            const uint TargetMaxSize = 250;
            var resizer = new ImageResizer(50, 0.50f);
            var sourceFiles = Directory.GetFiles(TestdataDirectory);
            Assert.Greater(sourceFiles.Length, 0);
            foreach (var sourceFile in sourceFiles)
            {
                Console.WriteLine(sourceFile);
                var sourceFileInfo = new FileInfo(sourceFile);
                var targetFileInfo = new FileInfo(Path.GetFileNameWithoutExtension(sourceFile) + "_s.jpg");
                Assert.DoesNotThrow(
                    () => resizer.Resize(sourceFileInfo.FullName, targetFileInfo.FullName, TargetMaxSize));
                Assert.IsTrue(targetFileInfo.Exists);
                Console.WriteLine("Compression Ratio : {0}", targetFileInfo.Length * 100.0 / sourceFileInfo.Length);
                Assert.Greater(targetFileInfo.Length, 0);
                Assert.Less(targetFileInfo.Length, sourceFileInfo.Length);

                using (var sourceImage = Image.FromFile(sourceFile))
                using (var targetImage = Image.FromFile(targetFileInfo.FullName))
                {
                    if (targetImage.Size.Height > targetImage.Size.Width)
                    {
                        Assert.AreEqual(targetImage.Size.Height, TargetMaxSize);
                    }
                    else
                    {
                        Assert.AreEqual(targetImage.Size.Width, TargetMaxSize);
                    }

                    // Aspect ratio
                    Assert.That(
                        targetImage.Size.Height / (double)targetImage.Size.Width, 
                        Is.EqualTo(sourceImage.Size.Height / (double)sourceImage.Size.Width).Within(0.009));
                }
            }
        }
Exemplo n.º 35
0
        public void 画像を100ピクセルにリサイズ()
        {
            if (!IsLocal)
                return;

            var files = Directory.GetFiles(TestContext.DeploymentDirectory, "*.jpg");
            var resizer = new ImageResizer();

            var baseDir = TestContext.TestDir;
            foreach (var file in files)
            {
                var name = Path.GetFileName(file);
                var path = Path.Combine(baseDir, "opt-" + name);

                // 実行できたなら結果は目視でいいんじゃん?
                resizer.Optimize(file, path);
                Assert.IsTrue(resizer.Resize(path, ResizeMode.Fit, 100, Path.Combine(baseDir, "fit-" + name)));
                Assert.IsTrue(resizer.Resize(path, ResizeMode.Clip, 100, Path.Combine(baseDir, "clip-" + name)));
            }
        }
Exemplo n.º 36
0
 private void GenerateResize(string cacheName, string resizeName, ResizeMode type, int size)
 {
     var resizer = new ImageResizer();
     var resizePath = CacheFullPath(resizeName);
     if (type != ResizeMode.Original && !File.Exists(resizePath))
     {
         resizer.Resize(cacheName, type, size, resizePath);
     }
 }
Exemplo n.º 37
0
        public void 小さすぎる画像を100ピクセルにリサイズ()
        {
            if (!IsLocal)
                return;

            var resizer = new ImageResizer();
            var baseDir = TestContext.TestDir;
            var name = "little.png";
            var path = Path.Combine(TestContext.DeploymentDirectory, name);
            Assert.IsTrue(resizer.Resize(path, ResizeMode.Fit, 100, Path.Combine(baseDir, "fit-" + name)));
            Assert.IsTrue(resizer.Resize(path, ResizeMode.Clip, 100, Path.Combine(baseDir, "clip-" + name)));
        }