예제 #1
0
        public ActionResult FileUpload(HttpPostedFileBase file)
        {
            if (file != null && file.ContentType.StartsWith("image/"))
            {
                WebImage img = new WebImage(file.InputStream);
                if (img.Width > 178)
                {
                    img.Resize(178, img.Height);
                }

                if (img.Height > 178)
                {
                    img.Resize(img.Width, 178);
                }

                //string path = "C:\\Users\\dzlatkova\\Desktop\\Images";

                //if (!Directory.Exists(path))
                //{
                //    DirectoryInfo di = Directory.CreateDirectory(path);
                //    di.Attributes &= ~FileAttributes.ReadOnly;
                //}

                //string filePath = Path.Combine(path, Path.GetFileName(file.FileName));

                //file.SaveAs(path);

                db.Employers.FirstOrDefault(x => x.UserId == WebSecurity.CurrentUserId).Picture = img.GetBytes();
                db.SaveChanges();
            }
            return RedirectToAction("Profile");
        }
        public ActionResult CreateImage(string format, string id)
        {
            var relName = $"~/App_Data/covers/{id}.jpg";
            var absName = Server.MapPath(relName);

            if (!System.IO.File.Exists(absName))
            {
                return HttpNotFound();
            }

            var img = new WebImage(absName);

            switch (format.ToLower())
            {
                case "thumb":
                    img.Resize(100, 1000).Write();
                    break;

                case "medium":
                    img.Resize(300, 3000)
                        .AddTextWatermark("Ingars Movie Database")
                        .AddTextWatermark("Ingars Movie Database", "White", padding: 7)
                        .Write();
                    break;

                default:
                    return HttpNotFound();
            }

            return new EmptyResult();
        }
        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);
        }
예제 #4
0
        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 });
            }
        }
 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 Edit(long id, HttpPostedFileBase boxFile, 
            HttpPostedFileBase bdate,
            HttpPostedFileBase box1, 
            HttpPostedFileBase box2, 
            HttpPostedFileBase box3,
            HttpPostedFileBase box4)
        {
			
            var item = GetSession.Get<Setting>(id);
            var homePath = Server.MapPath("~/public/userfiles/home/boximage.jpg");

            if (boxFile != null)
            {
                boxFile.SaveAs(string.Format(homePath));
            }

            homePath = Server.MapPath("~/public/userfiles/home/bdate.jpg");
            if (bdate != null)
            {
                bdate.SaveAs(string.Format(homePath));
            }

            homePath = Server.MapPath("~/public/userfiles/home/box1.jpg");
            if (box1 != null)
            {
                var image = new WebImage(box1.InputStream);
                image.Resize(500,212).Crop(1, 1).Save(string.Format(homePath));
            }

            homePath = Server.MapPath("~/public/userfiles/home/box2.jpg");
            if (box2 != null)
            {

                var image = new WebImage(box2.InputStream);
                image.Resize(500, 212).Crop(1, 1).Save(string.Format(homePath));
               
            }

            homePath = Server.MapPath("~/public/userfiles/home/box3.jpg");
            if (box3 != null)
            {
                var image = new WebImage(box3.InputStream);
                image.Resize(500, 212).Crop(1, 1).Save(string.Format(homePath));
            }

            homePath = Server.MapPath("~/public/userfiles/home/box4.jpg");
            if (box4 != null)
            {
                var image = new WebImage(box4.InputStream);
                image.Resize(500, 212).Crop(1, 1).Save(string.Format(homePath));
            }



			UpdateModel(item);

			GetSession.Update(item);

			return RedirectToAction("Edit");
		}
예제 #7
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));
        }
예제 #8
0
        public async Task<ActionResult> Edit(ProfileViewModel model, HttpPostedFileBase upload)
        {
            var user = _userManager.FindById(User.Identity.GetUserId());
            if (user == null)
            {
                return RedirectToAction("Start", "Main");
            }

            if (upload != null && upload.ContentLength > 0)
            {
                WebImage img = new WebImage(upload.InputStream);
                if (img.Width > 32)
                    img.Resize(32, 32);
                user.Avatar = img.GetBytes();
            }

            user.FirstName = model.FirstName;
            user.LastName = model.LastName;
            user.UserName = model.Username;
            user.Email = model.Email;

            await _userManager.UpdateAsync(user);

            return RedirectToAction("Details", "Profile");
        }
예제 #9
0
        public ActionResult Download(int id, bool? thumb)
        {
            var context = HttpContext;
            var mediaItem = Database.MediaItems.SingleOrDefault(m => m.Id == id);
            if (mediaItem == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }
            var filePath = Path.Combine(StorageRoot(mediaItem.MediaType), mediaItem.FileName);
            if (!System.IO.File.Exists(filePath))
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);

            const string contentType = "application/octet-stream";

            if (thumb.HasValue && thumb == true)
            {
                var img = new WebImage(filePath);
                if (img.Width > 120)
                    img.Resize(120, 110).Crop(1, 1);
                return new FileContentResult(img.GetBytes(), contentType)
                    {
                        FileDownloadName = mediaItem.FileName
                    };
            }
            else
            {
                return new FilePathResult(filePath, contentType)
                    {
                        FileDownloadName = mediaItem.FileName
                    };
            }
        }
예제 #10
0
		public async Task<ActionResult> CreateImage(string format, string id)
		{
			// koble til en storage-account
			var connectionString = CloudConfigurationManager.GetSetting("msu2015_AzureStorageConnectionString");
			var acct = CloudStorageAccount.Parse(connectionString);

			// åpne en konteiner
			var client = acct.CreateCloudBlobClient();

			var container = client.GetContainerReference("covers");
			
			// hente en fil
			var blob = container.GetBlockBlobReference($"{id}.jpg");

			if (!await blob.ExistsAsync()) return HttpNotFound();

			using (var ms = new MemoryStream())
			{
				// laste ned som stream
				await blob.DownloadToStreamAsync(ms);


				var img = new WebImage(ms);

				switch (format.ToLower())
				{
					case "thumb":
						img.Resize(100, 1000)
							.Write();
						return new EmptyResult();

					case "medium":
						img.Resize(300, 3000)
							.AddTextWatermark("Ingars Movie Database")
							.AddTextWatermark("Ingars Movie Database", "White", padding: 7)
							.Write();
						return new EmptyResult();

					default:
						return HttpNotFound();
				}
			}
		}
예제 #11
0
        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);
        }
        private string SubirImagen(WebImage imagen, int dimensionMaxima, string rutaDirectorio)
        {
            var isWide = imagen.Width > imagen.Height;
            var bigestDimension = isWide ? imagen.Width : imagen.Height;

            if (bigestDimension > dimensionMaxima)
            {
                if (isWide)
                    imagen.Resize(dimensionMaxima, ((dimensionMaxima * imagen.Height) / imagen.Width));
                else
                    imagen.Resize(((dimensionMaxima * imagen.Width) / imagen.Height), dimensionMaxima);
            }
            string nombreArchivo = GenerarUnNombreUnico(Path.GetFileName(imagen.FileName));

            GuardarImagen(imagen, rutaDirectorio, nombreArchivo);
            // GuardarImagenEnServidor();

            return nombreArchivo;
        }
예제 #13
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=\"\" />");
 }
예제 #14
0
        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);
        }
예제 #15
0
        private static WebImage ResizePhoto(PhotoSize photoSize, byte[] blobBytes)
        {
            var webImage = new WebImage(blobBytes);
            switch (photoSize)
            {
                case PhotoSize.Small:
                    webImage = webImage.Resize(64, 64, true, true);
                    break;

                case PhotoSize.Medium:
                    webImage = webImage.Resize(128, 128, true, true);
                    break;

                case PhotoSize.Large:
                    webImage = webImage.Resize(256, 256, true, true);
                    break;
            }

            return webImage;
        }
예제 #16
0
 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);
     }
 }
예제 #17
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);
        }
예제 #18
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);
 }
예제 #19
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);
            }
        }
예제 #20
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);
        }
예제 #21
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");
        }
예제 #22
0
        public ActionResult GetUserThumbnailImage(int userId, Guid userGuid)
        {
            try
            {
                UserDTO user = _managerService.UserDetails(userId, userGuid);
                var img = new WebImage(user.AvatarImage);
                img.Resize(32, 32, true, true);

                return File(img.GetBytes("png"), "image/png");
            }
            catch (Exception ex)
            {
                Logger.LogError("GetUserImage: Exception while retrieving user avatar image data", ex);
                return null;
            }
        }
예제 #23
0
        // GET: Photos
        public ActionResult GetSize(int id)
        {
            Staff staff = db.StaffList.Find(id);
            if (staff.Photo != null)
            {
                var img = new WebImage(staff.Photo);
                img.Resize(100, 100, true, true);
                var imgBytes = img.GetBytes();

                return File(imgBytes, "image/" + img.ImageFormat);
            }
            else
            {
                return null;
            }
        }
예제 #24
0
        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.GetFileName(fn);
                img.Save(Server.MapPath("~/" + newFileName));

                Account account = new Account(
                "lifedemotivator",
                "366978761796466",
                "WMYLmdaTODdm4U6VcUGhxapkcjI"
                );
                ImageUploadResult uploadResult = new ImageUploadResult();
                CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);
                var uploadParams = new ImageUploadParams()
                {
                    File = new FileDescription(Server.MapPath("~/" + newFileName)),
                    PublicId = User.Identity.Name + newFileName,
                };
                uploadResult = cloudinary.Upload(uploadParams);
                System.IO.File.Delete(Server.MapPath("~/" + newFileName));
                UrlAvatar = uploadResult.Uri.ToString();

                return Json(new { success = true, avatarFileLocation = UrlAvatar });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, errorMessage = "Unable to upload file.\nERRORINFO: " + ex.Message });
            }
        }
        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);
        }
        public ActionResult Show(Guid speakerId, int width, int height, string mode = "")
        {
            SpeakerPicture speakerPicture = service.TryGetPicture(speakerId);
            if (speakerPicture == null)
                return new HttpNotFoundResult();

            var image = new WebImage(speakerPicture.Picture);
            if (width > 0 && height > 0)
            {
                if (mode == "crop")
                    image = CropImage(image, width, height);
                else
                    image = image.Resize(width, height);
            }

            return File(image.GetBytes(), image.ImageFormat);
        }
예제 #27
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();
        }
예제 #29
0
 public StoredFile SaveUploadedFile(HttpPostedFileBase postedFile)
 {
     var maxHeight = 400.00;
     var img = new WebImage(postedFile.InputStream);
     double r = img.Height / maxHeight;
     var fileName = Guid.NewGuid().ToString();
     var fileExt = Path.GetExtension(postedFile.FileName);
     var fullSavePath = string.Format("{0}Content/Images/{1}{2}", AppDomain.CurrentDomain.BaseDirectory, fileName, fileExt).Replace('\\', '/');
     img.Resize((int)(img.Width / r), (int)(img.Height / r)).Save(fullSavePath);
     var file = new StoredFile
     {
         Description = "lorem ipsum",
         Name = fileName,
         Path = fullSavePath,
         Size = postedFile.ContentLength.ToString(),
         Type = fileExt,
         MimeType = postedFile.ContentType
     };
     return file;
 }
예제 #30
0
        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);
        }
예제 #31
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));
        }
예제 #32
-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);
        }