public ActionResult Create([Bind(Include = "Id,Title,Slug,Body,MediaURL")] Post post, HttpPostedFileBase fileUpload)
 {
     if (ModelState.IsValid)
     {
         //Restricting the valid file formats to images only
         if (fileUpload != null && fileUpload.ContentLength > 0)
         {
             if (!fileUpload.ContentType.Contains("image"))
             {
                 return new HttpStatusCodeResult(HttpStatusCode.UnsupportedMediaType);
             }
             //var fileName = Path.GetFileName(fileUpload.FileName);
             WebImage fileName = new WebImage(fileUpload.InputStream);
             if (fileName.Width > 500)
                 fileName.Resize(500, 500);
             //fileUpload.SaveAs(Path.Combine(Server.MapPath("~/assets/img/blog/"), fileName));
             fileName.Save("~/assets/img/blog/"+fileUpload.FileName);
             post.MediaURL = "~/assets/img/blog/" + fileUpload.FileName;
         }
         var cDate = DateTimeOffset.UtcNow;
         post.CreationDate = cDate.ToLocalTime();
         db.Posts.Add(post);
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(post);
 }
        public ActionResult Save(string t, string l, string h, string w, string fileName)
        {
            try
            {
                // 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, Path.GetFileName(fn));
                var newFileLocation = HttpContext.Server.MapPath(newFileName);
                if (Directory.Exists(Path.GetDirectoryName(newFileLocation)) == false)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(newFileLocation));
                }

                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 });
            }
        }
Example #3
0
        public ActionResult Create(CoursePostViewModel course)
        {
            if (ModelState.IsValid)
            {
                //saving image
                var image = new WebImage(course.File.InputStream);
                var imageName = Guid.NewGuid().ToString() + "." + image.ImageFormat;
                var path = Path.Combine(Server.MapPath("~/Content/Images"), WebSecurity.CurrentUserName, "Courses");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path = Path.Combine(path, imageName);
                image.Save(path);

                //saving course
                var dbCourse = ViewModelIntoEntity(course);
                dbCourse.CreatedDate = DateTime.Now;
                dbCourse.LastModifiedDate = DateTime.Now;
                dbCourse.Published = false;
                dbCourse.ImageName = imageName;
                dbCourse.ImageUrl = Path.Combine("~/Content/Images", WebSecurity.CurrentUserName, "Courses", imageName);
                db.Courses.Add(dbCourse);
                db.SaveChanges();

                return RedirectToAction("Courses", "Dashboard");
            }

            ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", course.CategoryId);
            ViewBag.InstructorId = WebSecurity.CurrentUserId;
            return View(course);
        }
Example #4
0
        public ActionResult Create(Makale makale, string etiketler, HttpPostedFileBase Foto)
        {
            if (ModelState.IsValid)
            {
                if (Foto != null)
                {
                    WebImage img      = new System.Web.Helpers.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);
                    makale.Foto = "/Uploads/MakaleFoto/" + newfoto;
                }
                if (etiketler != null)
                {
                    string[] etiketdizi = etiketler.Split(',');
                    foreach (var i in etiketdizi)
                    {
                        var yenietiket = new Etiket {
                            EtiketAdi = i
                        };
                        db.Etikets.Add(yenietiket);
                        makale.Etikets.Add(yenietiket);
                    }
                }
                makale.UyeId  = Convert.ToInt32(Session["uyeid"]);
                makale.Okunma = 1;
                db.Makales.Add(makale);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(makale));
        }
Example #5
0
        /// <summary>
        /// Saves an image to the temp directory with a given name
        /// </summary>
        /// <param name="image">Image to save</param>
        /// <param name="fileName">Name of the file to save as</param>
        /// <returns>Where the image is saved at</returns>
        public virtual string Save(WebImage image, string fileName)
        {
            var path = GetFilePath(fileName);
            image.Save(path);

            return path;
        }
        public ActionResult EditImage(EditorInputModel editor)
        {
            string fileName = editor.Profile.ImageUrl;
            var image = new WebImage(HttpContext.Server.MapPath("/Images/Temp/") + fileName);

            double ratio = editor.Width / 620;
            //the values to crop off.
            double top = editor.Top * ratio;
            double left = editor.Left * ratio;
            double bottom = editor.Height - editor.Bottom * ratio;
            double right = editor.Width - editor.Right * ratio;

            image.Crop((int)top, (int)left, (int)bottom, (int)right);

            //the image size I need at the end
            image.Resize(620, 280);
            image.Save(Path.Combine(HttpContext.Server.MapPath("/Images/News"), fileName));
            System.IO.File.Delete(Path.Combine(HttpContext.Server.MapPath("/Images/Temp/"), fileName));

            var imageThumb = image;
            imageThumb.Resize(65, 50);
            imageThumb.Save(Path.Combine(HttpContext.Server.MapPath("/Images/News/Thumb"), fileName));
            editor.Profile.ImageUrl = fileName;
            return View("Index", editor.Profile);
        }
        public void CreateThumbnail(String filename, String directory, int width, int height, String prefix = "thumb_")
        {
            var image = new WebImage(Path.Combine(directory, filename));

            int newWidth = image.Width < image.Height ? image.Width*height/image.Height : width;
            int newHeight = image.Width < image.Height ? height : image.Height*width/image.Width;

            image.Resize(newWidth, newHeight, true).Crop(1, 1);
            image.Save(Path.Combine(directory, String.Format("{0}{1}", prefix, filename)), image.ImageFormat);
        }
Example #8
0
 private ActionResult UploadImage(HttpPostedFileBase img, string sessionName)
 {
     var extension = Path.GetExtension(img.FileName);
     var tempFileName = Guid.NewGuid();
     var saveUrl = "~/ProfileImages/" + tempFileName + extension;
     var image = new WebImage(img.InputStream);
     image.Resize(150, 150);
     image.Save(saveUrl);
     Session.Add(sessionName, saveUrl);
     return Content("<img src=\"/ProfileImages/" + tempFileName + extension + "\" alt=\"\" />");
 }
        public static void CreateThumbnail(HttpPostedFileBase image, string folder)
        {
            var thumbnail = new WebImage(image.InputStream);
            System.Diagnostics.Debug.WriteLine(thumbnail.FileName);

            var fullPath = Path.Combine("~/" + folder + "/Thumbnails/", image.FileName);

            thumbnail.Resize(thumbWidth, thumbHeight, true);

            thumbnail.Save(fullPath, thumbnail.ImageFormat);
        }
 private static void SaveImage(HttpPostedFileBase file, string filename)
 {
     WebImage img = new WebImage(file.InputStream);
     if (img.Width > Settings.Default.MaxAuthorImageWidth)
     {
         int newWidth = Settings.Default.MaxAuthorImageWidth;
         float aspectRatio = (float)img.Width / (float)img.Height;
         int newHeight = Convert.ToInt32(newWidth / aspectRatio);
         img.Resize(newWidth, newHeight).Crop(1, 1);
         img.Save(filename);
     }
 }
        public string saveImageToServer(WebImage image)
        {
            string folderPath = Server.MapPath(@"~/Images");
            if (!Directory.Exists(folderPath))
                Directory.CreateDirectory(folderPath);

            String newFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(image.FileName);
            String fullPath = @"Images/" + newFileName;

            image.Save(@"~/" + fullPath);
            return newFileName;
        }
Example #12
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);
        }
Example #13
0
 public static void uploadImage(dynamic uploadedFile,ref String guids)
 {
     var fileSavePath = "";
     BinaryReader b = new BinaryReader(uploadedFile.InputStream);
       byte[] binData = b.ReadBytes(uploadedFile.ContentLength);
       WebImage img= new WebImage(binData);
       var guid=Guid.NewGuid().ToString();
       guids = guids +""+guid+",";
       fileSavePath = System.Web.HttpContext.Current.Server.MapPath("~/images/property/" +
         guid);
       img.Resize(imageWidth,imageHeight,true);
       img.Save(fileSavePath,"jpg",true);
 }
Example #14
0
        public static void CropFile(string name, string diretorio, List<ImagensLayout.Tamanho> tamanhos)
        {
            var path = MontaPath(diretorio, name);

            foreach (var item in tamanhos)
            {
                if (item.Nome == "Original")
                    continue;

                var imagem = new WebImage(path);
                var pathFotoCropada = MontaPath(diretorio, item.Altura + "x" + item.Largura + "_" + name);
                imagem.Resize(item.Largura, item.Altura);
                imagem.Save(pathFotoCropada);
            }
        }
Example #15
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);
        }
Example #16
0
        public ActionResult Crop(ImageModel imageModel)
        {
            WebImage image = new WebImage(_PATH + imageModel.ImagePath);
            var height = image.Height;
            var width = image.Width;
            var top = imageModel.Top;
            var left = imageModel.Left;
            var bottom = imageModel.Bottom;
            var right = imageModel.Right;

            image.Crop(top, left, height - bottom, width - right);
            image.Resize(140, 200, false, false);
            image.Save(_PATH + imageModel.ImagePath);

            return RedirectToAction("Index");
        }
Example #17
0
        public static string BigDetailImageSave(WebImage image, int width = 600, int height = 600)
        {
            if (image != null)
            {
                if (image.Width > width)
                {
                    image.Resize(width, ((height * image.Height) / image.Width));
                }

                var filename = Path.GetFileName(image.FileName);
                var filepath = Path.Combine(DefaulDetailImg, filename);
                image.Save(filepath);

                return filepath.TrimStart('~');

            }
            return "";
        }
        public ActionResult Index(HttpPostedFileBase arquivo)
        {
            if (ModelState.IsValid)
            {
                if (arquivo != null)
                {
                    if (arquivo.ContentLength > (1024 * 1024))
                    {
                        ModelState.AddModelError("arquivo", "O tamanho do arquivo não pode ser maior que 1Mb");
                        return View();
                    }

                    var supportedTypes = new[] { "jpg", "jpeg", "png" };

                    var fileExt = Path.GetExtension(arquivo.FileName).Substring(1);

                    if (!supportedTypes.Contains(fileExt.ToLower()))
                    {
                        ModelState.AddModelError("arquivo",
                                                 "Tipo de arquivo invalido, use somente arquivos jpg, jpeg ou png");
                        return View();
                    }

                    //var fileName = Path.GetFileName(arquivo.FileName);//Nome Original do arquivo
                    var fileName = Guid.NewGuid().ToString() + "." + fileExt;//Nome unico

                    var path = Path.Combine(Server.MapPath("~/Content/Uploads"), fileName);

                    //arquivo.SaveAs(path); //somente se não for editar a foto, como no codigo abaixo

                    WebImage imagem = new WebImage(arquivo.InputStream);
                    imagem.Resize(350, 350);
                    //imagem.AddTextWatermark("Cleyton Ferrari");
                    imagem.AddImageWatermark("Content/Uploads/logo.png", 50, 50, "Right", "Bottom", 50, 2);
                    //imagem.Crop(100, 100, 100, 100);
                    imagem.FlipHorizontal();
                    imagem.Save(path);

                    ViewBag.imagem = "Content/Uploads/" + fileName;
                }
            }
            return View();
        }
        public ActionResult Edit(EditorInputModel editor)
        {
            string fileName = editor.Profile.ImageUrl;
            Console.WriteLine("test");
            var image = new WebImage(HttpContext.Server.MapPath("/Images/") + fileName);
            //the values to crop off.
            double top = editor.Top;
            double left = editor.Left;
            double bottom = editor.Bottom;
            double right = editor.Right;

            image.Crop((int)top, (int)left, (int)bottom, (int)right);

            //the image size I wanted
            image.Resize(620, 280);
            image.Save(Path.Combine(HttpContext.Server.MapPath("/Images/News"), fileName));
            System.IO.File.Delete(Path.Combine(HttpContext.Server.MapPath("/Images/"), fileName));
            editor.Profile.ImageUrl = fileName;
            return View("Index", editor.Profile);
        }
        public List<ImageInfo> UploadAll(HttpContextBase contentBase)
        {
            List<ImageInfo> resultList = new List<ImageInfo>();
            var request = contentBase.Request;

            var pathOnServer = Path.Combine(_storageRoot);
            var thumbPath = Path.Combine(pathOnServer, "thumbs");

            Directory.CreateDirectory(pathOnServer);
            Directory.CreateDirectory(thumbPath);

            for (int i = 0; i < request.Files.Count; i++)
            {
                var file = request.Files[i];

                var filePath = Path.Combine(pathOnServer, Path.GetFileName(file.FileName));
                file.SaveAs(filePath);

                //Create thumb
                string[] imageArray = file.FileName.Split('.');
                if (imageArray.Length != 0)
                {
                    var extension = imageArray[imageArray.Length - 1];
                    if (extension == "jpg" || extension == "png") //Do not create thumb if file is not an image
                    {
                        var thumbFileName = file.FileName + ".80x80.jpg";
                        var thumbFilePath = Path.Combine(thumbPath, thumbFileName);
                        using (MemoryStream stream = new MemoryStream(File.ReadAllBytes(filePath)))
                        {
                            var thumbnail = new WebImage(stream).Resize(80, 80);
                            thumbnail.Save(thumbFilePath, "jpg");
                        }
                    }
                }
                resultList.Add(GetImageInfo(file.FileName, file.ContentLength, file.FileName));
            }
            return resultList;
        }
Example #21
0
 public int UploadAjax(Stream InputStream, string fileName, bool thumbnail = true)
 {
     int num = -1;
     using (StreamReader streamReader = new StreamReader(InputStream))
     {
         string[] strArray = streamReader.ReadToEnd().Split(new char[1] { ',' });
         string str1 = strArray[0].Split(new char[1] { ':' })[1];
         byte[] numArray = Convert.FromBase64String(strArray[1]);
         if (numArray.Length > 0)
         {
             if (str1.Contains("image"))
             {
                 string imageFormat = str1.Split(new char[1] { ';' })[0].Replace("image/", "");
                 WebImage webImage = new WebImage(numArray);
                 if (webImage != null)
                 {
                     string str2 = "upload_" + (object)DateTime.Now.Ticks;
                     webImage.Save(this._Path + str2, imageFormat, true);
                     if (thumbnail)
                     {
                         webImage.Resize(this._ThumbHeight, this._ThumbWidth, true, false);
                         webImage.Crop(1, 1, 0, 0).Save(this._ThumbnailPath + str2, imageFormat, true);
                     }
                     num = 1;
                 }
             }
             else
             {
                 string str2 = "upload_" + (object)DateTime.Now.Ticks + new FileInfo(fileName).Extension;
                 TFile.StreamToFile((Stream)new MemoryStream(numArray), this._Path + str2);
                 num = 1;
             }
         }
     }
     return num;
 }
Example #22
0
        public ActionResult Edit(ProfileViewModel editedUser)
        {
            if (ModelState.IsValid)
            {
                var user = db.Users.Find(editedUser.UserId);
                if (user == null)
                {
                    return HttpNotFound();
                }

                if (editedUser.File != null)
                {
                    var image = new WebImage(editedUser.File.InputStream);
                    if (image != null)
                    {
                        var imageName = Guid.NewGuid().ToString() + "." + image.ImageFormat;
                        var path = Path.Combine(Server.MapPath("~/Content/Images"), WebSecurity.CurrentUserName, "Profile");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        path = Path.Combine(path, imageName);
                        image.Save(path);
                        user.ImageName = imageName;
                        user.ImageUrl = Path.Combine("~/Content/Images", WebSecurity.CurrentUserName, "Profile", imageName);
                    }
                }
                user.FullName = editedUser.FullName;
                user.Description = editedUser.Description;
                user.DateOfBirth = editedUser.DateOfBirth;
                db.SaveChanges();
                return RedirectToAction("Edit");
            }

            return View(editedUser);
        }
Example #23
0
 /// <summary>
 /// Сохраняет файл по указанному пути, преобразуя его в JPEG формат
 /// </summary>
 /// <param name="file">Файл</param>
 /// <param name="fullPath">путь</param>
 public static void SaveAs(HttpPostedFileBase file, string fullPath)
 {
     var webImage = new WebImage(file.InputStream);
     webImage.Save(fullPath, "jpeg");
 }
Example #24
0
        public ActionResult CreateStep3(ImageInput editor)
        {
            var image = new WebImage("~" + editor.Image.ImageUrl);
            var height = image.Height;
            var width = image.Width;
            var tempUrl = editor.Image.ImageUrl;
            var saveUrl = @BlogGlobals.SlideImageFolder + Path.GetFileName(image.FileName);

            image.Crop((int)editor.Top, (int)editor.Left, (int)(height - editor.Bottom), (int)(width - editor.Right));
            image.Resize(190, 190, true, false);
            image.Save(saveUrl);
            System.IO.File.Delete(Server.MapPath(tempUrl));

            ViewBag.PostId = new SelectList(db.Posts, "PostId", "Title");
            ViewBag.imageUrl = saveUrl;

            Slide slide = new Slide();

            return View("CreateStep3", slide);
        }
Example #25
0
        public ActionResult Edit(MembershipOfSite membershipofsite, HttpPostedFileBase pictureFile)
        {
            if (ModelState.IsValid)
            {
                if (pictureFile != null)
                {
                    string fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(pictureFile.FileName);
                    WebImage WI = new WebImage(pictureFile.InputStream);
                    WI.Resize(200, 200, false, false);
                    WI.Save(Server.MapPath("~/Files/UsersImage/" + fileName));
                    if (System.IO.File.Exists(Server.MapPath("~/Files/UsersImage/" + membershipofsite.Picture)))
                        System.IO.File.Delete(Server.MapPath("~/Files/UsersImage/" + membershipofsite.Picture));
                    membershipofsite.Picture = fileName;
                }
                db.Entry(membershipofsite).State = EntityState.Modified;

                db.SaveChanges();
                return RedirectToAction("details");
            }
            return View(membershipofsite);
        }
Example #26
0
        public ActionResult Create(MembershipOfSite membershipofsite, HttpPostedFileBase pictureFile, string confirmPassword, string password, string securityQuestion, string answerSecurityQuestion)
        {
            if (ModelState.IsValid)
            {
                //if (!Roles.RoleExists("Bronze"))
                //    Roles.CreateRole("Bronze");
                AccountController ac = new AccountController();
                string Result = ac.CreateAccount(membershipofsite.Username, password,
                    membershipofsite.Email, securityQuestion, answerSecurityQuestion);
                if (Result != "Success")
                {
                    ModelState.AddModelError("", Result);
                    ViewBag.SQ = securityQuestion;
                    ViewBag.ASQ = answerSecurityQuestion;
                    ViewBag.SecurityQuestion = new SelectList(db.SecurityQuestions, "QuestionText", "QuestionText", securityQuestion);
                    return View(membershipofsite);
                }
                else
                {
                    if (!Roles.RoleExists("Admin"))
                        Roles.CreateRole("Admin");
                    Roles.AddUserToRole(membershipofsite.Username, "Admin");
                    membershipofsite.ID = Guid.NewGuid();
                    membershipofsite.DateSignUp = DateTime.Now;
                    var gradeforreg = db.Assistances.Select(x => x.GradeForReister).FirstOrDefault();
                    if (gradeforreg != null)
                    {
                        membershipofsite.Grade += Convert.ToInt32(gradeforreg);
                    }
                    if (pictureFile != null)
                    {
                        string fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(pictureFile.FileName);
                        WebImage WI = new WebImage(pictureFile.InputStream);
                        WI.Resize(200, 200, false, false);
                        WI.Save(Server.MapPath("~/Files/UsersImage/" + fileName));
                        membershipofsite.Picture = fileName;
                    }
                    db.MembershipOfSites.Add(membershipofsite);
                    db.SaveChanges();
                    if (Roles.IsUserInRole("Admin"))
                        return RedirectToAction("Index");
                    else
                    {
                        ac.LogIn(new LoginViewModel() { Password = password, UserName = membershipofsite.Username, RememberMe = false }, null);

                        return RedirectToAction("Index", "home");
                    }
                }
            }
            ViewBag.SecurityQuestion = new SelectList(db.SecurityQuestions, "QuestionText", "QuestionText", securityQuestion);
            return View(membershipofsite);
        }
Example #27
0
        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);
        }
Example #28
0
        public ActionResult AddGown(int password, int id_catgory, int id_season, string is_long, int price, string is_light, int color, int num_of_dress, string fileset, string arrFiles, string arrSizes)
        {
            System.Web.Helpers.WebImage photo = null;

            var imagePath = "";


            int error = 0;

            var q = db.Renters.FirstOrDefault(p => p.password == password);

            if (ModelState.IsValid && q != null)
            {
                string[] arrayFiles;
                string[] arraySizes;
                string[] arrfilenames;
                arraySizes = arrSizes.Split(' ').ToArray();
                arrayFiles = arrFiles.Split('?').ToArray();
                int idGown = 0;
                foreach (Gowns currentGown in db.Gowns)
                {
                    idGown = currentGown.id_gown;
                }
                if (arraySizes.Count() > 2)
                {
                    Sets set = new Sets();
                    int  id  = 0;
                    foreach (Sets currentset in db.Sets)
                    {
                        id = currentset.id_set;
                    }
                    set.num_of_set = arraySizes.Count() - 1;
                    set.id_set     = id + 1;
                    arrfilenames   = arrayFiles[0].Split('\\').ToArray();
                    var filenameSet = Guid.NewGuid().ToString() + "_" + arrfilenames[arrfilenames.Count() - 1];
                    set.picture = filenameSet;
                    photo       = WebImage.GetImageFromRequest("fileset");
                    if (photo != null)
                    {
                        //Path.GetFileName(photo.FileName);
                        imagePath = @"Images\" + filenameSet;

                        photo.Save(@"~\" + imagePath);
                    }
                    int i = 0;

                    foreach (string size in arraySizes)
                    {
                        if (size != "")
                        {
                            Gowns gown = new Gowns();
                            arrfilenames    = arrayFiles[i].Split('\\').ToArray();
                            gown.id_gown    = idGown + 1;
                            gown.id_renter  = q.id_renter;
                            gown.id_catgory = id_catgory;
                            var filename = Guid.NewGuid().ToString() + "_" + arrfilenames[arrfilenames.Count() - 1];
                            gown.picture   = filename.ToString();
                            gown.id_season = id_season;
                            if (is_long == "ארוך")
                            {
                                gown.is_long = true;
                            }
                            else
                            {
                                gown.is_long = false;
                            }
                            gown.price = price;
                            if (is_light == "בהיר")
                            {
                                gown.is_light = true;
                            }
                            else
                            {
                                gown.is_light = false;
                            }
                            gown.color  = color;
                            gown.id_set = set.id_set;
                            gown.size   = int.Parse(size);
                            photo       = WebImage.GetImageFromRequest("file" + ++i);
                            if (photo != null)
                            {
                                //photo.Resize((int)(photo.Width*0.8), (int)(photo.Height * 0.8));
                                //Path.GetFileName(photo.FileName);
                                imagePath = @"Images\" + filename;

                                photo.Save(@"~\" + imagePath);
                            }
                            db.Sets.Add(set);
                            db.Gowns.Add(gown);
                        }
                    }
                }
                else
                {
                    Gowns gown = new Gowns();
                    gown.id_gown    = idGown + 1;
                    gown.id_renter  = q.id_renter;
                    gown.id_catgory = id_catgory;
                    arrfilenames    = arrayFiles[0].Split('\\').ToArray();
                    var filename = Guid.NewGuid().ToString() + "_" + arrfilenames[arrfilenames.Count() - 1];
                    gown.picture   = filename.ToString();
                    gown.id_season = id_season;
                    if (is_long == "ארוך")
                    {
                        gown.is_long = true;
                    }
                    else
                    {
                        gown.is_long = false;
                    }
                    gown.price = price;
                    if (is_light == "בהיר")
                    {
                        gown.is_light = true;
                    }
                    else
                    {
                        gown.is_light = false;
                    }
                    gown.color  = color;
                    gown.id_set = 1;
                    gown.size   = int.Parse(arraySizes[0]);

                    photo = WebImage.GetImageFromRequest("file1");
                    if (photo != null)
                    {
                        //Path.GetFileName(photo.FileName);
                        imagePath = @"Images\" + filename;

                        photo.Save(@"~\" + imagePath);
                    }

                    db.Gowns.Add(gown);
                }
                db.SaveChanges();
                // return RedirectToAction("Index");
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                if (q == null)
                {
                    error = 1;
                }
            }
            ViewBag.id_catgory = new SelectList(db.Catgories, "id_catgory", "catgory");
            ViewBag.id_renter  = new SelectList(db.Renters, "id_renter", "fname");
            ViewBag.id_season  = new SelectList(db.Seasons, "id_season", "season");
            ViewBag.id_season  = new SelectList(db.Seasons, "id_season", "season");
            ViewBag.id_set     = new SelectList(db.Sets, "id_set", "id_set");
            ViewBag.color      = new SelectList(db.Colors, "id_color", "color");

            return(RedirectToAction("AddGown", new { error = error }));
        }
        public ActionResult UploadProfile()
        {
            var user = new Guid(User.Identity.GetUserId());
            if (!System.IO.Directory.Exists(Server.MapPath("~/Profiles/Tutors/" + user)))
            {
                System.IO.Directory.CreateDirectory(Server.MapPath("~/Profiles/Tutors/" + user));
            }
            string path = "";
            var fileName = "";
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                fileName = Path.GetFileName(file.FileName);

                path = Path.Combine(Server.MapPath("~/Profiles/Tutors/" + user), fileName);
                //file.SaveAs(path);

                WebImage img = new WebImage(file.InputStream);

                if (img.Width > 1000)
                    img.Resize(1000, 1000);
                img.Save(path);


                Tutor loaddb = db.Tutors.Find(user);
                loaddb.ProfileImage = "/Profiles/Tutors/" + user + "/" + fileName;
                db.Entry(loaddb).State = EntityState.Modified;
                db.SaveChanges();
            }

            return Json(new { result = "/Profiles/Tutors/" + user + "/" + fileName });

        }
Example #30
0
        private string SaveMainPicture(string kittenName, Stream file)
        {
            string path = String.Empty;

            // Verify that the user selected a file
            if (file != null && file.Length > 0 && !String.IsNullOrEmpty(kittenName))
            {
                var sizeImage = new WebImage(file).Crop(1,1).Resize(300, 300, false, true);

                path = _picturesLinksConstructor.GetKittenImagePath(kittenName);
                RemoveFile(Server.MapPath(path));
                sizeImage.Save(Server.MapPath(path));
            }

            return path;
        }
Example #31
0
        private string SaveImage(string filename, WebImage image)
        {
            try
            {
                RemoveFile(filename);
                // save the file.
                image.Save(filename);
            }
            catch (Exception)
            {
                filename = String.Empty;
            }

            return filename;
        }
Example #32
0
        public ActionResult Create([Bind(Include = "Slide_Id,Titolo,Sottotitolo,Sfondo,Posizione,Pubblica", Exclude = "Descrizione")] Slide slide, HttpPostedFileBase file)
        {
            FormCollection collection = new FormCollection(Request.Unvalidated().Form);

            slide.Descrizione = collection["Descrizione"];
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    try
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        slide.Sfondo = fileName;
                        db.Slides.Add(slide);
                        db.SaveChanges();

                        var path = Path.Combine(Server.MapPath("~/Content/Immagini/Slides/"), fileName);
                        System.Web.Helpers.WebImage img = new System.Web.Helpers.WebImage(file.InputStream);
                        var larghezza = img.Width;
                        var altezza   = img.Height;
                        var rapportoO = larghezza / altezza;
                        var rapportoV = altezza / larghezza;
                        if (altezza > 1900 | larghezza > 1900)
                        {
                            if (rapportoO >= 1)
                            {
                                ViewBag.Message = "Attendi la fine del download...";
                                img.Resize(1900, 1900 / rapportoO);
                                img.Save(path);
                                ViewBag.Message = "Download immagine orizzontale avvenuto con successo. Dimensione immagine originale: larghezza " + larghezza + " Altezza " + altezza;
                            }
                            else
                            {
                                ViewBag.Message = "Attendi la fine del download...";
                                img.Resize(800 / rapportoV, 800);
                                img.Save(path);
                                ViewBag.Message = "Download immagine verticale avvenuto con successo. Dimensione immagine: larghezza " + larghezza + "Altezza" + altezza;
                            }
                        }
                        else
                        {
                            if (rapportoO >= 1)
                            {
                                ViewBag.Message = "Attendi la fine del download...";
                                img.Save(path);
                                ViewBag.Message = "Download immagine orizzontale avvenuto con successo. Dimensione immagine originale: larghezza " + larghezza + " Altezza " + altezza;
                            }
                            else
                            {
                                ViewBag.Message = "Attendi la fine del download...";
                                img.Save(path);
                                ViewBag.Message = "Download immagine verticale avvenuto con successo. Dimensione immagine: larghezza " + larghezza + "Altezza" + altezza;
                            }
                        }
                        return(RedirectToAction("Index", "Slides"));
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Message = "ERROR:" + ex.Message.ToString();
                    }
                }
                else
                {
                    ViewBag.Message = "Devi scegliere un file";
                    return(View());
                }


                return(RedirectToAction("Index"));
            }

            return(View(slide));
        }
Example #33
-1
        public static void Save(Stream inputStream, string fileName, out string imagePath, out string thumpPath, out byte[] binary, out string mimeType)
        {
            ImageSetting setting = GetSetting();

            var fullPath = HttpContext.Current.Server.MapPath("/");

            CreateFolder(setting);

            if (inputStream == null) throw new ArgumentNullException("inputStream");
            var image = new WebImage(inputStream);

            binary = image.GetBytes();
            mimeType = fileName.GetMimeType();

            image.FileName = fileName;

            if (image.Width > 500)
            {
                image.Resize(500, ((500 * image.Height) / image.Width));
            }

            var fn = Guid.NewGuid() + "-" + CommonHelper.RemoveMarks(Path.GetFileName(fileName));

            thumpPath = imagePath = fn;

            image.Save(fullPath + setting.ImagePath + fn);

            image.Resize(132, 102);
            image.Save(fullPath + setting.ThumpPath + "/1__" + fn);

            image.Resize(53, 53);
            image.Save(fullPath + setting.ThumpPath + "/2__" + fn);
        }