public ActionResult Edit(int id, HttpPostedFileBase Foto, Makale makale)
        {
            try
            {
                var makales = db.Makales.Where(m => m.MakaleId == id).SingleOrDefault();
                ViewBag.foto = makales.Foto;
                if (Foto != null)
                {
                    if (System.IO.File.Exists(Server.MapPath(makales.Foto)))
                    {
                        System.IO.File.Delete(Server.MapPath(makales.Foto));
                    }
                    WebImage img      = new WebImage(Foto.InputStream);
                    FileInfo fotoinfo = new FileInfo(Foto.FileName);

                    string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
                    img.Resize(800, 350);
                    img.Save("~/Uploads/MakaleFoto/" + newfoto);
                    makales.Foto       = "/Uploads/MakaleFoto/" + newfoto;
                    makales.Baslik     = makale.Baslik;
                    makales.Icerik     = makale.Icerik;
                    makales.KategoriId = makale.KategoriId;
                    makales.Tarih      = makale.Tarih;
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
                if (Foto == null)
                {
                    makales.Foto       = ViewBag.foto;
                    makales.Baslik     = makale.Baslik;
                    makales.Icerik     = makale.Icerik;
                    makales.KategoriId = makale.KategoriId;
                    makales.Tarih      = makale.Tarih;
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }


                return(View());
            }
            catch
            {
                ViewBag.KategoriId = new SelectList(db.Kategoris, "KategoriId", "KategoriAdi", makale.KategoriId);
                return(View(makale));
            }
        }
        public ActionResult KitapDüzenle(int id, Urun urun, HttpPostedFileBase Resim, HttpPostedFileBase Demo, HttpPostedFileBase SesDosyasi)
        {
            var kitap = db.Uruns.Where(x => x.UrunID == id).SingleOrDefault();

            if (Resim != null & Demo != null & SesDosyasi != null)
            {
                if (System.IO.File.Exists(Server.MapPath(urun.Resim)))
                {
                    System.IO.File.Delete(Server.MapPath(urun.Resim));
                }
                WebImage img      = new WebImage(Resim.InputStream);
                FileInfo fotoinfo = new FileInfo(Resim.FileName);
                string   newfoto  = Guid.NewGuid().ToString() + fotoinfo.Extension;
                img.Resize(800, 350);
                img.Save("~/Uploads/Resim/" + newfoto);
                urun.Resim = "../Uploads/Resim/" + newfoto;

                string fileName = Path.GetFileName(Demo.FileName);
                int    fileSize = Demo.ContentLength;
                int    Size     = fileSize / 1000000;
                Demo.SaveAs(Server.MapPath("~/Uploads/Demo/" + fileName));
                urun.Demo = "../Uploads/Demo/" + fileName;

                string fileNamee = Path.GetFileName(Demo.FileName);
                int    fileSizee = Demo.ContentLength;
                int    Sizee     = fileSize / 1000000;
                SesDosyasi.SaveAs(Server.MapPath("~/Uploads/SesDosyasi/" + fileName));
                urun.SesDosyası = "../Uploads/SesDosyasi/" + fileName;

                ViewBag.KategoriID   = new SelectList(db.Kategoris, "KategoriID", "KategoriAdi", urun.KategoriID);
                kitap.KategoriID     = urun.KategoriID;
                kitap.DinlenmeSayisi = urun.DinlenmeSayisi;
                kitap.EklenmeTarihi  = urun.EklenmeTarihi;
                kitap.Ozet           = urun.Ozet;
                kitap.Seslendiren    = urun.Seslendiren;
                kitap.Süre           = urun.Süre;
                kitap.UrunAdi        = urun.UrunAdi;
                kitap.Yazar          = urun.Yazar;
                kitap.Demo           = urun.Demo;
                kitap.Resim          = urun.Resim;
                kitap.SesDosyası     = urun.SesDosyası;
                db.SaveChanges();
            }

            return(RedirectToAction("Index"));
        }
Beispiel #3
0
        public ActionResult Create(User user, HttpPostedFileBase photo)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (photo != null)
                    {
                        WebImage img       = new WebImage(photo.InputStream);
                        FileInfo photoinfo = new FileInfo(photo.FileName);

                        string newphoto = Guid.NewGuid().ToString() + photoinfo.Extension;
                        img.Resize(150, 150);
                        img.Save("~/Uploads/UserFoto/" + newphoto);
                        user.photo = "/Uploads/UserFoto/" + newphoto;

                        user.authority_id = 2;
                        user.credit       = 0;
                        db.Users.Add(user);
                        db.SaveChanges();
                        Session["userid"]   = user.user_id;
                        Session["email"]    = user.email;
                        Session["username"] = user.u_name;

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError("photo", "chose a photo");
                    }
                }
                catch (DbEntityValidationException e)
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        Response.Write(string.Format("Entity türü \"{0}\" şu hatalara sahip \"{1}\" Geçerlilik hataları:", eve.Entry.Entity.GetType().Name, eve.Entry.State));
                        foreach (var ve in eve.ValidationErrors)
                        {
                            Response.Write(string.Format("- Özellik: \"{0}\", Hata: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                        }
                        Response.End();
                    }
                }
            }
            return(View(user));
        }
Beispiel #4
0
        public string SaveAsMinified(string rootPath, string fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }
            //(,)[^,]*$
            //TODO move from here
            fileName = Regex.Replace(fileName, @"(.*)([.])(.+)$", m => m.Groups[1].Value + ".min." + m.Groups[3].Value);
            var saveLocationMin  = SaveLocation;
            var imageLocationMin = saveLocationMin + $@"\{fileName}";
            var newImage         = new WebImage(Root + rootPath);

            newImage.Resize(64, 64);
            newImage.Save(Root + imageLocationMin);
            return(imageLocationMin);
        }
Beispiel #5
0
        public ActionResult SaveQuestion(HttpPostedFileBase file, FormCollection frm)
        {
            QuestionDM queDM = new QuestionDM();
            Question   que   = queDM.FindQuestionByID(int.Parse(frm["queID"]));

            que.Answer  = frm["TxtAns"];
            que.Content = frm["TxtContent"];
            que.Time    = int.Parse(frm["TxtTime"]);
            que.AnsA    = frm["TxtC1"];
            que.AnsB    = frm["TxtC2"];
            que.AnsC    = frm["TxtC3"];
            que.AnsD    = frm["TxtC4"];

            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    string path = Path.Combine(Server.MapPath("~/resources/images/QuestionImages"),
                                               Path.GetFileName(file.FileName));
                    file.SaveAs(path);

                    // WebImage belong to WebHelper class which supports the crop, flip, watermark operation etc.
                    WebImage img = new WebImage(file.InputStream);
                    if (img.Width > 1200)
                    {
                        img.Resize(1200, 600);
                    }
                    img.Save(path);

                    que.Image = file.FileName;
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            }
            else if (file == null)
            {
                que.Image = "default.png";
            }
            queDM.UpdateQuestion(que);

            Quiz q = new QuizBank().FindQuizByID(que.QuizID);

            return(View("EditQuiz", q));
        }
Beispiel #6
0
 public ActionResult ReferenceUpdate(Reference reference, HttpPostedFileBase Image)
 {
     if (ModelState.IsValid)
     {
         if (Image != null)
         {
             WebImage img      = new WebImage(Image.InputStream);
             FileInfo fotoInfo = new FileInfo(Image.FileName);
             string   newFoto  = Guid.NewGuid().ToString() + fotoInfo.Extension;
             img.Resize(800, 400);
             img.Save("~/Areas/Admin/Uploads/ReferenceFoto/" + newFoto);
             reference.Image = "/Areas/Admin/Uploads/ReferenceFoto/" + newFoto;
         }
     }
     _referenceService.Update(reference);
     return(RedirectToAction("Index", "Reference"));
 }
        public ActionResult Edit([Bind(Include = "kullaniciID,yetkiID,memleketID,adsoyad,kullaniciAdi,mail,sifre,telefon,resim")] kullanicilar kullanicilar, string sifre, HttpPostedFileBase resim, int id)
        {
            var md5pass = sifre;

            if (ModelState.IsValid)
            {
                var uye1 = db.kullanicilars.Where(k => k.kullaniciID == id).SingleOrDefault();

                if (resim != null)
                {
                    if (System.IO.File.Exists(Server.MapPath(kullanicilar.resim)))
                    {
                        System.IO.File.Delete(Server.MapPath(uye1.resim));
                    }

                    WebImage img = new WebImage(resim.InputStream);

                    FileInfo resiminfo = new FileInfo(resim.FileName);

                    string newfoto = Guid.NewGuid().ToString() + resiminfo.Extension;
                    img.Resize(150, 150);
                    img.Save("~/Uploads/uyeler/" + newfoto);
                    uye1.resim = "/Uploads/uyeler/" + newfoto;
                }

                uye1.adsoyad      = kullanicilar.adsoyad;
                uye1.kullaniciAdi = kullanicilar.kullaniciAdi;
                uye1.mail         = kullanicilar.mail;
                uye1.sifre        = Crypto.Hash(md5pass, "MD5");

                uye1.telefon = kullanicilar.telefon;
                db.SaveChanges();
                Session["kullaniciadi"] = kullanicilar.kullaniciID;

                return(RedirectToAction("Index", "Home", new { id = uye1.kullaniciID }));



                db.Entry(kullanicilar).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.memleketID = new SelectList(db.memlekets, "memleketID", "memleketAdi", kullanicilar.memleketID);

            return(View(kullanicilar));
        }
Beispiel #8
0
        public ActionResult Ekle(menu model, HttpPostedFileBase ResimURL)
        {
            model.kategori_id = Convert.ToInt32(TempData["id"]);
            if (ResimURL != null)
            {
                WebImage img          = new WebImage(ResimURL.InputStream);
                FileInfo imginfo      = new FileInfo(ResimURL.FileName);
                string   menuSayfalar = Guid.NewGuid().ToString() + imginfo.Extension;
                img.Resize(370, 355, preserveAspectRatio: false);
                img.Save("~/Uploads/Menu/" + menuSayfalar);
                model.resim = "/Uploads/Menu/" + menuSayfalar;
            }

            sorgu.MenuKaydet(model);
            TempData["Uyari"] = "İşlem başarılı";
            return(RedirectToAction("/Ekle/" + model.kategori_id + ""));
        }
        /// <summary>
        /// Uploading and resizing an image, Currently it is used to upload member profile pic, provider service banner image and category image
        /// </summary>
        /// <param name="originalImage"></param>
        /// <param name="imagePrefix"></param>
        /// <param name="rootPath"></param>
        /// <param name="server"></param>
        /// <param name="_unitOfWork"></param>
        /// <param name="memberId"></param>
        /// <param name="serviceId"></param>
        public void UploadImage(HttpPostedFileBase originalImage, string imagePrefix, string rootPath, HttpServerUtilityBase server, GenericUnitOfWork _unitOfWork, int memberId, int productId = 0, int categoryId = 0)
        {
            bool existsOriginal = System.IO.Directory.Exists(server.MapPath("~/" + rootPath + "Original/"));

            if (!existsOriginal)
            {
                System.IO.Directory.CreateDirectory(server.MapPath("~/" + rootPath + "Original/"));
            }
            originalImage.SaveAs(server.MapPath("~/" + rootPath + "Original/" + imagePrefix + originalImage.FileName));
            // Large size for service banner image
            if (productId != 0)
            {
                WebImage img1 = new WebImage(server.MapPath("~/" + rootPath + "Original/" + imagePrefix + originalImage.FileName));
                img1.Resize(849, 320);
                bool exists = System.IO.Directory.Exists(server.MapPath("~/" + rootPath + "Large/"));
                if (!exists)
                {
                    System.IO.Directory.CreateDirectory(server.MapPath("~/" + rootPath + "Large/"));
                }
                img1.Save(Path.Combine(server.MapPath("~/" + rootPath + "Large/" + imagePrefix + originalImage.FileName)));
            }

            WebImage img2 = new WebImage(server.MapPath("~/" + rootPath + "Original/" + imagePrefix + originalImage.FileName));

            img2.Resize(274, 175);
            bool exists2 = System.IO.Directory.Exists(server.MapPath("~/" + rootPath + "Medium/"));

            if (!exists2)
            {
                System.IO.Directory.CreateDirectory(server.MapPath("~/" + rootPath + "Medium/"));
            }
            img2.Save(Path.Combine(server.MapPath("~/" + rootPath + "Medium/" + imagePrefix + originalImage.FileName)));

            WebImage img3 = new WebImage(server.MapPath("~/" + rootPath + "Original/" + imagePrefix + originalImage.FileName));

            img3.Resize(68, 68);
            bool exists3 = System.IO.Directory.Exists(server.MapPath("~/" + rootPath + "Small/"));

            if (!exists3)
            {
                System.IO.Directory.CreateDirectory(server.MapPath("~/" + rootPath + "Small/"));
            }
            img3.Save(Path.Combine(server.MapPath("~/" + rootPath + "Small/" + imagePrefix + originalImage.FileName)));

            System.IO.File.Delete(server.MapPath("~/" + rootPath + "Original/" + imagePrefix + originalImage.FileName));
        }
Beispiel #10
0
        private static string SaveTemporaryAvatarFileImage(HttpPostedFileBase file, string serverPath, string fileName)
        {
            var img   = new WebImage(file.InputStream);
            var ratio = img.Height / (double)img.Width;

            img.Resize(AvatarScreenWidth, (int)(AvatarScreenWidth * ratio));

            var fullFileName = Path.Combine(serverPath, fileName);

            if (System.IO.File.Exists(fullFileName))
            {
                System.IO.File.Delete(fullFileName);
            }

            img.Save(fullFileName);
            return(Path.GetFileName(img.FileName));
        }
Beispiel #11
0
        public ActionResult Create(Blog blog, HttpPostedFileBase ResimURL)
        {
            if (ResimURL != null)
            {
                WebImage img     = new WebImage(ResimURL.InputStream);
                FileInfo imginfo = new FileInfo(ResimURL.FileName);

                string blogimgname = Guid.NewGuid().ToString() + imginfo.Extension;
                img.Resize(600, 400);
                img.Save("~/Uploads/Blog/" + blogimgname);

                blog.ResimURL = "/Uploads/Blog/" + blogimgname;
            }
            db.Blog.Add(blog);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #12
0
 public ActionResult NewsUpdate(News news, HttpPostedFileBase Image)
 {
     if (ModelState.IsValid)
     {
         if (Image != null)
         {
             WebImage img      = new WebImage(Image.InputStream);
             FileInfo fotoInfo = new FileInfo(Image.FileName);
             string   newFoto  = Guid.NewGuid().ToString() + fotoInfo.Extension;
             img.Resize(1080, 720);
             img.Save("~/Areas/Admin/Uploads/NewsFoto/" + newFoto);
             news.Image = "/Areas/Admin/Uploads/NewsFoto/" + newFoto;
         }
     }
     _newsService.Update(news);
     return(RedirectToAction("News", "News"));
 }
        public ActionResult Save(string t, string l, string h, string w, string fileName)
        {
            try
            {
                // Calculate dimensions
                var top    = Convert.ToInt32(t.Replace("-", string.Empty).Replace("px", string.Empty));
                var left   = Convert.ToInt32(l.Replace("-", string.Empty).Replace("px", string.Empty));
                var height = Convert.ToInt32(h.Replace("-", string.Empty).Replace("px", string.Empty));
                var width  = Convert.ToInt32(w.Replace("-", string.Empty).Replace("px", string.Empty));

                // Get file from temporary folder
                var fn = Path.Combine(this.Server.MapPath(MapTempFolder), Path.GetFileName(fileName));

                // ...get image and resize it, ...
                var img = new WebImage(fn);
                img.Resize(width, height);

                // ... crop the part the user selected, ...
                img.Crop(top, left, img.Height - top - AvatarStoredHeight, img.Width - left - AvatarStoredWidth);

                // ... delete the temporary file,...
                System.IO.File.Delete(fn);

                // ... and save the new one.
                var userId            = this.HttpContext.User.Identity.GetUserId();
                var imageFromDatabase = this.avatars.GetById(userId);
                imageFromDatabase.FileName    = img.FileName;
                imageFromDatabase.ContentType = "image/" + img.ImageFormat.ToLower();
                imageFromDatabase.Content     = img.GetBytes();
                this.avatars.Save();

                var newFileName     = Path.Combine(AvatarPath, Path.GetFileName(fn));
                var newFileLocation = this.HttpContext.Server.MapPath(newFileName);
                if (Directory.Exists(Path.GetDirectoryName(newFileLocation)) == false)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(newFileLocation));
                }

                img.Save(newFileLocation);
                return(this.Json(new { success = true, avatarFileLocation = newFileName }));
            }
            catch (Exception ex)
            {
                return(this.Json(new { success = false, errorMessage = "Unable to upload file.\nERRORINFO: " + ex.Message }));
            }
        }
        public ActionResult Create(Makale makale, string Etiketler, HttpPostedFileBase Foto)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (null != Foto)
                    {
                        WebImage img      = new WebImage(Foto.InputStream);
                        FileInfo fotoInfo = new FileInfo(Foto.FileName);
                        string   newfoto  = Guid.NewGuid().ToString() + fotoInfo.Extension;
                        img.Resize(750, 300);
                        img.Save("~/Uploads/MakaleFoto/" + newfoto);
                        makale.Foto = "/Uploads/MakaleFoto/" + newfoto.ToString();
                    }
                    if (null != Etiketler)
                    {
                        string[] etiketdizi = Etiketler.Split(',');

                        foreach (var item in etiketdizi)
                        {
                            var Yenietiket = new Etiket {
                                EtiketAdi = item
                            };
                            db.Etiket.Add(Yenietiket);
                            makale.Etiket.Add(Yenietiket);
                        }
                    }
                    makale.UyeId  = Convert.ToInt32(Session["uyeid"].ToString());
                    makale.Okunma = 0;
                    makale.Tarih  = DateTime.Now;
                    db.Makale.Add(makale);
                    db.SaveChanges();

                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(RedirectToAction("Index"));
                }
            }
            catch
            {
                return(RedirectToAction("Index"));
            }
        }
        public ActionResult Edit(int id, SiteInformation siteInformation, HttpPostedFileBase Logo, HttpPostedFileBase SiteIcon)
        {
            if (ModelState.IsValid)
            {
                var information = db.SiteInformation.Where(x => x.Id == id).FirstOrDefault();

                if (Logo != null)
                {
                    if (System.IO.File.Exists(Server.MapPath(information.Logo)))
                    {
                        System.IO.File.Delete(Server.MapPath(information.Logo));
                    }
                    WebImage img     = new WebImage(Logo.InputStream);
                    FileInfo imginfo = new FileInfo(Logo.FileName);
                    string   nm      = Logo.FileName + imginfo.Extension;
                    img.Resize(600, 400);
                    img.Save("~/Uploads/SiteInformation/" + nm);

                    information.Logo = "/Uploads/SiteInformation/" + nm;
                }

                if (SiteIcon != null)
                {
                    if (System.IO.File.Exists(Server.MapPath(information.SiteIcon)))
                    {
                        System.IO.File.Delete(Server.MapPath(information.SiteIcon));
                    }
                    WebImage img     = new WebImage(SiteIcon.InputStream);
                    FileInfo imginfo = new FileInfo(SiteIcon.FileName);
                    string   nm      = SiteIcon.FileName + imginfo.Extension;
                    img.Resize(600, 400);
                    img.Save("~/Uploads/SiteInformation/" + nm);

                    information.SiteIcon = "/Uploads/SiteInformation/" + nm;
                }

                information.Author      = siteInformation.Author;
                information.Description = siteInformation.Description;
                information.Id          = siteInformation.Id;

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(siteInformation));
        }
Beispiel #16
0
 public ActionResult SliderUpdate(Slider slider, HttpPostedFileBase Image)
 {
     if (ModelState.IsValid)
     {
         if (Image != null)
         {
             WebImage img      = new WebImage(Image.InputStream);
             FileInfo fotoInfo = new FileInfo(Image.FileName);
             string   newFoto  = Guid.NewGuid().ToString() + fotoInfo.Extension;
             img.Resize(1920, 1080);
             img.Save("~/Areas/Admin/Uploads/SliderFoto/" + newFoto);
             slider.Image = "/Areas/Admin/Uploads/SliderFoto/" + newFoto;
         }
     }
     _sliderService.Update(slider);
     return(RedirectToAction("AddSlider", "Slider"));
 }
Beispiel #17
0
        public ActionResult UpdateBook(UpdateBook book)
        {
            if (!ModelState.IsValid)
            {
                GetAuthorAndCategories();
                return(View(book));
            }

            using (var context = new DataContext())
            {
                var updateBook = context.Books.Include("Categories").Include("Author").Include("Author.Country").FirstOrDefault(b => b.Id == book.Id);

                if (book.BookCover != null)
                {
                    string   bookCover = Guid.NewGuid().ToString().Substring(0, 10) + "_" + System.IO.Path.GetFileName(book.BookCover.FileName);
                    WebImage img       = new WebImage(book.BookCover.InputStream);
                    img.Resize(380, 600);
                    img.Save(Server.MapPath("~/Content/images/book/" + bookCover));
                    updateBook.Image = bookCover;
                }

                if (book.BookFile != null)
                {
                    string bookPath = Guid.NewGuid().ToString().Substring(0, 10) + "_" + System.IO.Path.GetFileName(book.BookFile.FileName);
                    book.BookFile.SaveAs(Server.MapPath("~/Content/books/" + bookPath));
                    updateBook.BookPath = bookPath;
                }

                updateBook.Name            = book.Name;
                updateBook.Slug            = book.Name.GenerateSlug();
                updateBook.Year            = book.Year;
                updateBook.NumberPages     = book.NumberPages;
                updateBook.Author          = context.Authors.FirstOrDefault(a => a.Id == book.AuthorId);
                updateBook.Description     = book.Description;
                updateBook.View            = 0;
                updateBook.Rating          = book.Rating;
                updateBook.ForAuthorize    = book.ForAuthorize;
                updateBook.TodayBestChoice = book.TodayBestChoice;
                updateBook.Create          = DateTime.Now;
                updateBook.Categories      = context.Categories.Where(c => c.Id == book.CategoryId).ToList();

                context.SaveChanges();
            }

            return(Redirect("/admin/books"));
        }
Beispiel #18
0
        public void EditComboPanel(int id, string menuTag, string underMenuTag, int style, HttpPostedFileBase thisFile, string align, string header, string context)
        {
            using (this.ef = new CMSDbEntities())
            {
                var combo = this.ef.Panels.Find(id);
                if (combo == null || combo.CombomPanel == null)
                {
                    return;
                }

                combo.MenuTag                  = menuTag;
                combo.UnderMenuTag             = underMenuTag;
                combo.StyleSheet               = style;
                combo.CombomPanel.PictureAlign = align;
                combo.CombomPanel.Header       = header;
                combo.CombomPanel.Context      = context;

                if (thisFile != null && thisFile.ContentLength > 50)
                {
                    var lenght    = thisFile.ContentLength;
                    var tempimage = new byte[lenght];

                    thisFile.InputStream.Read(tempimage, 0, lenght);

                    var wi    = new WebImage(tempimage);
                    var width = wi.Width;
                    if (wi.Width > 279)
                    {
                        var ratio = 279 / width;
                        if (ratio != 0)
                        {
                            wi.Resize(279, Convert.ToInt32(wi.Height * ratio));
                            combo.CombomPanel.ImageData = wi.GetBytes();
                            combo.CombomPanel.ImageType = thisFile.ContentType;
                        }
                    }
                    else
                    {
                        combo.CombomPanel.ImageData = wi.GetBytes();
                        combo.CombomPanel.ImageType = thisFile.ContentType;
                    }
                }

                this.ef.SaveChanges();
            }
        }
Beispiel #19
0
        public ActionResult Create([Bind(Include = "ProductAccessoryId,ProductId,Color,Price,ImageFile,Quantiny")] ProductAccessory productAccessory, HttpPostedFileBase imageFront, HttpPostedFileBase imageBack, HttpPostedFileBase imageSide)
        {
            if (ModelState.IsValid)
            {
                db.ProductAccessories.Add(productAccessory);
                db.SaveChanges();
                if (imageFront != null)
                {
                    //Resize Image
                    WebImage img = new WebImage(imageFront.InputStream);
                    img.Resize(500, 1000);

                    var    filePathOriginal = Server.MapPath("/Assets/user/images");
                    var    fileName         = productAccessory.ProductId + "-" + productAccessory.Color + "-1" + ".jpg";
                    string savedFileName    = Path.Combine(filePathOriginal, fileName);
                    img.Save(savedFileName);
                }
                if (imageBack != null)
                {
                    //Resize Image
                    WebImage img = new WebImage(imageBack.InputStream);
                    img.Resize(500, 1000);

                    var    filePathOriginal = Server.MapPath("/Assets/user/images");
                    var    fileName         = productAccessory.ProductId + "-" + productAccessory.Color + "-2" + ".jpg";
                    string savedFileName    = Path.Combine(filePathOriginal, fileName);
                    img.Save(savedFileName);
                }
                if (imageSide != null)
                {
                    //Resize Image
                    WebImage img = new WebImage(imageSide.InputStream);
                    img.Resize(500, 1000);

                    var    filePathOriginal = Server.MapPath("/Assets/user/images");
                    var    fileName         = productAccessory.ProductId + "-" + productAccessory.Color + "-3" + ".jpg";
                    string savedFileName    = Path.Combine(filePathOriginal, fileName);
                    img.Save(savedFileName);
                }
                return(RedirectToAction("Index"));
            }

            ViewBag.ProductId = new SelectList(db.Products, "ProductId", "ProductName", productAccessory.ProductId);
            return(View(productAccessory));
        }
    protected void CreateAnimal(object sender, EventArgs e)
    {
        WebsiteUser Op          = (WebsiteUser)Session["User"];
        WebImage    photo       = null;
        var         newFileName = "";
        var         imagePath   = "";

        if (IsValid)
        {
            photo = WebImage.GetImageFromRequest();
            if (photo != null)
            {
                newFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(photo.FileName);
                imagePath   = @"Images\" + newFileName;
                photo.Resize(width: 250, height: 300, preserveAspectRatio: true, preventEnlarge: true);
                photo.Save(@"~\" + imagePath);
                ErrorMessage.Visible = true;

                Animal subject = new Animal(Nome.Text, Espécie.Text, Raca.Text, Convert.ToUInt32(Idade.Text.ToString()), Convert.ToUInt32(Peso.Text.ToString()), Convert.ToUInt32(Temperatura.Text.ToString()), imagePath, Op.ClientID, Convert.ToUInt32(DropDownTipo.Text));

                switch (Animal.Add(subject))
                {
                case 0:
                    ErrorMessage.Text = "Erro ao registar novo animal. Por favor verifique se os dados que inseriu são válidos.";
                    break;

                case 1:
                    ErrorMessage.Text = "O animal foi registdo com sucesso mas houve um problema ao enviar a foto.";
                    break;

                case 2:
                    ErrorMessage.Text = "Registo efectuado com sucesso.";
                    break;

                default:
                    ErrorMessage.Text = "Erro desconhecido.";
                    break;
                }
            }
            else
            {
                ErrorMessage.Text = "Foto inválida.";
            }
        }
    }
        public ActionResult SaveImage(string t, string l, string h, string w, string fileName, int counter = 0)
        {
            try
            {
                if (fileName != null)
                {
                    // Calculate dimensions
                    var top    = Convert.ToInt32(t.Replace("-", "").Replace("px", ""));
                    var left   = Convert.ToInt32(l.Replace("-", "").Replace("px", ""));
                    var height = Convert.ToInt32(h.Replace("-", "").Replace("px", ""));
                    var width  = Convert.ToInt32(w.Replace("-", "").Replace("px", ""));

                    // Get file from temporary folder
                    var fn = Path.Combine(Server.MapPath(MapTempFolder), Path.GetFileName(fileName));
                    // ...get image and resize it, ...
                    var img = new WebImage(fn);
                    img.Resize(width, height);
                    // ... crop the part the user selected, ...
                    img.Crop(top, left, img.Height - top - AvatarStoredHeight, img.Width - left - AvatarStoredWidth);
                    // ... delete the temporary file,...
                    System.IO.File.Delete(fn);
                    // ... and save the new one.

                    var newFileName     = Path.Combine(AvatarPath, GetFinalFileName(Path.GetFileName(fn)));
                    var newFileLocation = HttpContext.Server.MapPath(newFileName);
                    var directoryName   = Path.GetDirectoryName(newFileLocation);
                    if (directoryName != null && !Directory.Exists(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    img.Save(newFileLocation);
                    return(Json(new
                    {
                        success = true,
                        avatarFileLocation = newFileName
                    }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, errorMessage = "Unable to upload file.\nERRORINFO: " + ex.Message }));
            }
            return(null);
        }
 public ActionResult Edit(int ID, HttpPostedFileBase Foto, OgretmenVM model)
 {
     using (OIDbEntities db = new OIDbEntities())
     {
         if (!ModelState.IsValid)
         {
             OgretmenVM ogr = new OgretmenVM()
             {
                 Bolumlers    = db.Bolumlers.ToList(),
                 Cinsiyetlers = db.Cinsiyetlers.ToList(),
                 Ogretmenlers = model.Ogretmenlers,
                 Sehirlers    = db.Sehirlers.ToList()
             };
             return(View(ogr));
         }
         var ogretmen = db.Ogretmenlers.Where(x => x.ID == ID).SingleOrDefault();
         if (ogretmen == null)
         {
             return(HttpNotFound());
         }
         if (Foto != null)
         {
             if (System.IO.File.Exists(Server.MapPath(ogretmen.Fotograf)))
             {
                 System.IO.File.Delete(Server.MapPath(ogretmen.Fotograf));
             }
             WebImage img     = new WebImage(Foto.InputStream);
             FileInfo info    = new FileInfo(Foto.FileName);
             string   newFoto = Guid.NewGuid().ToString() + info.Extension;
             img.Resize(150, 300);
             img.Save("~/OgretmenFoto/" + newFoto);
             ogretmen.Fotograf = "/OgretmenFoto/" + newFoto;
         }
         ogretmen.Adres       = model.Ogretmenlers.Adres;
         ogretmen.Adsoyad     = model.Ogretmenlers.Adsoyad;
         ogretmen.BolumID     = model.Ogretmenlers.BolumID;
         ogretmen.CinsiyetID  = model.Ogretmenlers.CinsiyetID;
         ogretmen.DogumTarihi = model.Ogretmenlers.DogumTarihi;
         ogretmen.DogumYeri   = model.Ogretmenlers.DogumYeri;
         ogretmen.Mail        = model.Ogretmenlers.Mail;
         ogretmen.Tel         = model.Ogretmenlers.Tel;
         db.SaveChanges();
         return(RedirectToAction("List"));
     }
 }
        private string SaveTemporaryAvatarFileImage(HttpPostedFileBase file, string serverPath, string fileName)
        {
            var    img   = new WebImage(file.InputStream);
            double ratio = (double)img.Height / (double)img.Width;

            string fullFileName = Path.Combine(serverPath, fileName);

            img.Resize(400, (int)(400 * ratio)); // ToDo - Change the value of the width of the image oin the screen

            if (System.IO.File.Exists(fullFileName))
            {
                System.IO.File.Delete(fullFileName);
            }

            img.Save(fullFileName);

            return(Path.GetFileName(img.FileName));
        }
Beispiel #24
0
        public ActionResult picture(int id)
        {
            var fac = new CarFactory();
            var car = fac.Cars.Where(p => p.Car_ID == id).FirstOrDefault();


            if (car == null)
            {
                return(HttpNotFound());
            }


            var img = new WebImage(string.Format("~/Content/Images/{0}.jpg", car.ImageName));

            img.Resize(100, 100);

            return(File(img.GetBytes(), "image/jpg"));
        }
        private WebImage CropImage(WebImage image, int width, int height)
        {
            var    cropper = new Cropping();
            double multi   = cropper.GetMultiplicator(new Size(image.Width, image.Height), new Size(width, height));

            double fWidth  = image.Width * multi;
            double fHeight = image.Height * multi;

            image = image.Resize((int)fWidth, (int)fHeight, preserveAspectRatio: false);
            int iWidth  = image.Width;
            int iHeight = image.Height;
            int top     = Math.Max((iHeight - height) / 2, 0);
            int left    = Math.Max((iWidth - width) / 2, 0);
            int bottom  = Math.Max(iHeight - (height + top), 0);
            int right   = Math.Max(iWidth - (width + left), 0);

            return(image.Crop(top, left, bottom, right));
        }
Beispiel #26
0
        public void ResizeAndSave(Size newSize, string newPath = null)
        {
            if (string.IsNullOrEmpty(pathToFile))
            {
                return;
            }

            if (!File.Exists(pathToFile))
            {
                return;
            }

            WebImage webImage = new WebImage(pathToFile);

            webImage.Resize(newSize.Width, newSize.Height);

            webImage.Save(newPath ?? pathToFile);
        }
        public ActionResult Create(Category category, HttpPostedFileBase image)
        {
            if (image != null)
            {
                WebImage img      = new WebImage(image.InputStream);
                FileInfo fotoInfo = new FileInfo(image.FileName);

                string newFoto = Guid.NewGuid().ToString() + fotoInfo.Extension;
                img.Resize(800, 350);
                img.Save("~/Uploads/Category/" + newFoto);
                category.Picture = "/Uploads/Category/" + newFoto;
            }

            category.Active = true;
            _categoryService.Add(category);

            return(RedirectToAction("Index"));
        }
Beispiel #28
0
        public ActionResult imagem(HttpPostedFileBase __file)
        {
            if (__file != null)
            {
                ImageMedia _imagem = new ImageMedia();
                _imagem.Imagem         = new byte[__file.ContentLength];
                _imagem.ImagemMimeType = __file.ContentType;
                __file.InputStream.Read(_imagem.Imagem, 0, __file.ContentLength);

                // toDo: redimensionar a imagem
                WebImage webimg = new WebImage(__file.InputStream);
                webimg.Resize(100, 100);

                return(RedirectToAction("Exibir", new { _imagem.Id }));
            }

            return(View());
        }
Beispiel #29
0
 public ActionResult Edit(About about, HttpPostedFileBase resimUrl, HttpPostedFileBase cvFile)
 {
     if (ModelState.IsValid)
     {
         var a = context.About.Find(about.Id);
         if (resimUrl != null)
         {
             if (System.IO.File.Exists(Server.MapPath(a.ResimUrl)))
             {
                 System.IO.File.Delete(Server.MapPath(a.ResimUrl));
             }
             WebImage img       = new WebImage(resimUrl.InputStream);
             FileInfo imgInfo   = new FileInfo(resimUrl.FileName);
             string   resimYolu = Guid.NewGuid().ToString() + imgInfo.Extension;
             img.Resize(500, 500, false, false);
             img.Save("~/Content/MyWebSite/img/" + resimYolu);
             about.ResimUrl = "/Content/MyWebSite/img/" + resimYolu;
             a.ResimUrl     = about.ResimUrl;
         }
         if (cvFile != null)
         {
             if (System.IO.File.Exists(Server.MapPath(a.MyCV)))
             {
                 System.IO.File.Delete(Server.MapPath(a.MyCV));
             }
             FileInfo cvFileInfo = new FileInfo(cvFile.FileName);
             string   cvFileYolu = Guid.NewGuid().ToString() + cvFileInfo.Extension;
             cvFile.SaveAs(Server.MapPath("~/Content/MyWebSite/myResume/" + cvFileYolu));
             about.MyCV = "/Content/MyWebSite/myResume/" + cvFileYolu;
             a.MyCV     = about.MyCV;
         }
         a.Name      = about.Name;
         a.Surname   = about.Surname;
         a.MyJob     = about.MyJob;
         a.BirthDate = about.BirthDate;
         a.MyJobFA   = about.MyJobFA;
         context.SaveChanges();
         return(RedirectToAction("Index"));
     }
     else
     {
         return(View(about));
     }
 }
        public ActionResult Add(ProfileRegisterModel profileRegistered)
        {
            var    title = "";
            string content;
            var    profile = Mapper.Map <ProfileRegisterModel, Profile>(profileRegistered);

            try
            {
                if (profileRegistered.UploadPhoto != null)
                {
                    WebImage img = new WebImage(profileRegistered.UploadPhoto.InputStream);
                    if (img.Width > 200 || img.Height > 200)
                    {
                        img.Resize(200, 200);
                    }

                    profile.Photo = img.GetBytes();
                }
            }
            catch (Exception)
            {
                title   = "Error!";
                content = "Formato de Imagen Incorrecto";
                _viewMessageLogic.SetNewMessage(title, content, ViewMessageType.ErrorMessage);
                return(RedirectToAction("Add"));
            }
            var query =
                _profileRepository.Filter(e => e.FullName == profile.FullName);

            if (query.Any())
            {
                title   = "Error!";
                content = "El Perfil ya existe.";
                _viewMessageLogic.SetNewMessage(title, content, ViewMessageType.ErrorMessage);
                return(RedirectToAction("Index"));
            }

            var profileCreated = _profileRepository.Create(profile);

            title   = "Perfil Agregado";
            content = profileCreated.FullName + "ha sido guardado exitosamente.";
            _viewMessageLogic.SetNewMessage(title, content, ViewMessageType.SuccessMessage);
            return(RedirectToAction("Index"));
        }
        public void ResizePreservesFormat()
        {
            // Arrange
            WebImage image = new WebImage(_PngImageBytes);
            MemoryStream output = null;
            Action<string, byte[]> saveAction = (_, content) => { output = new MemoryStream(content); };

            // Act
            image.Resize(200, 100, preserveAspectRatio: true, preventEnlarge: true);

            // Assert
            Assert.Equal(image.ImageFormat, "png");
            image.Save(GetContext(), saveAction, @"x:\1.png", null, false);

            using (Image modified = Image.FromStream(output))
            {
                Assert.Equal(ImageFormat.Png, modified.RawFormat);
            }
        }
        public void ResizePreservesResolution()
        {
            MemoryStream output = null;
            Action<string, byte[]> saveAction = (_, content) => { output = new MemoryStream(content); };

            WebImage image = new WebImage(_PngImageBytes);

            image.Resize(100, 50, preserveAspectRatio: true, preventEnlarge: true);

            image.Save(GetContext(), saveAction, @"x:\ResizePreservesResolution.jpg", "jpeg", forceWellKnownExtension: true);
            using (Image original = Image.FromStream(new MemoryStream(_PngImageBytes)))
            {
                using (Image modified = Image.FromStream(output))
                {
                    Assert.Equal(original.HorizontalResolution, modified.HorizontalResolution);
                    Assert.Equal(original.VerticalResolution, modified.VerticalResolution);
                }
            }
        }
        public void ResizePreservesRatio()
        {
            WebImage image = new WebImage(_JpgImageBytes);

            image.Resize(200, 100, preserveAspectRatio: true, preventEnlarge: true);

            Assert.Equal(130, image.Width);
            Assert.Equal(100, image.Height);
        }
        public void ResizeThrowsOnIncorrectWidthOrHeight()
        {
            WebImage image = new WebImage(_JpgImageBytes);

            Assert.ThrowsArgumentGreaterThan(
                () => image.Resize(-1, 100, preserveAspectRatio: true, preventEnlarge: true),
                "width",
                "0");

            Assert.ThrowsArgumentGreaterThan(
                () => image.Resize(100, -1, preserveAspectRatio: true, preventEnlarge: true),
                "height",
                "0");
        }
        public void ResizeAndRotateDoesOperationsInRightOrder()
        {
            WebImage image = new WebImage(_JpgImageBytes);
            image.Resize(200, 100, preserveAspectRatio: true, preventEnlarge: true).RotateLeft();

            Assert.Equal(100, image.Width);
            Assert.Equal(130, image.Height);
        }
        public void ClonePreservesAllInformation()
        {
            WebImage image = new WebImage(_JpgImageBytes);
            image.Resize(200, 100, preserveAspectRatio: true, preventEnlarge: true).RotateLeft();

            // this should preserve list of transformations
            WebImage cloned = image.Clone();

            Assert.Equal(100, cloned.Width);
            Assert.Equal(130, cloned.Height);
        }
        public void ResizePreventsEnlarge()
        {
            WebImage image = new WebImage(_JpgImageBytes);

            int height = image.Height;
            int width = image.Width;

            image.Resize(width * 2, height, preserveAspectRatio: true, preventEnlarge: true);
            Assert.Equal(width, image.Width);
            Assert.Equal(height, image.Height);
        }
        public void MultipleCombinedOperationsExecuteInRightOrder()
        {
            WebImage image = new WebImage(_JpgImageBytes);
            image.Resize(200, 100, preserveAspectRatio: true, preventEnlarge: true).RotateLeft();
            image.Crop(top: 10, right: 10).AddTextWatermark("plan9");

            Assert.Equal(90, image.Width);
            Assert.Equal(120, image.Height);
        }