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);
 }
Ejemplo n.º 2
0
        public void Create(Gallery gallery = null,HttpPostedFileBase file = null,int galId=0)
        {
            byte[] newdata = null;

            if (gallery != null)
            {
                var gall = new Gallery();
                gall.GalleryMimeType = file.ContentType;
                newdata = new WebImage(file.InputStream).GetBytes(null);
                gall.GalleryTitle = gallery.GalleryTitle;
                gall.GalleryData = newdata;
                this.db.Galleries.Add(gall);
            }
            else {

                Image image2 = new Image();
                string str = Regex.Replace(file.FileName, @"\.\w+", string.Empty);
                image2.ImageTitle = str;
                image2.Sortindex = image2.ID+1;
                image2.GalleryID = galId;
                image2.ImageMimeType = file.ContentType;
                newdata = new WebImage(file.InputStream).GetBytes(null);
                image2.ImageData = newdata;
                this.db.Images.Add(image2);
            }
               db.SaveChanges();
        }
Ejemplo n.º 3
0
        public ActionResult Crop(Guid id)
        {
            if (!db.Resources.Any(x => x.ID == id)) throw new HttpException(404, "Resource not found.");
            Resource res = db.Resources.Single(x => x.ID == id);
            if (!res.Type.StartsWith("image")) return Content("You cannot crop a non-image resource!");

            string path = Path.Combine(Server.MapPath("~/ResourceUploads"), id.ToString());
            FileStream stream = new FileStream(path, FileMode.Open);
            if (stream.Length == 0) throw new HttpException(503, "An internal server error occured whilst fetching the resource.");

            byte[] streamBytes = new byte[stream.Length];
            stream.Read(streamBytes, 0, (int)stream.Length);
            stream.Close();

            WebImage img = new WebImage(streamBytes);
            CropForm form = new CropForm
            {
                ResourceID = id,
                Type = res.Type,
                Source = res.Source,
                SourceTextColorID = res.SourceTextColorID,
                OrigWidth = img.Width,
                OrigHeight = img.Height
            };
            return View(form);
        }
Ejemplo n.º 4
0
        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);
        }
Ejemplo n.º 5
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");
        }
Ejemplo n.º 6
0
        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");
		}
Ejemplo n.º 7
0
 public int UploadForm(HttpPostedFileBase file, bool thumbnail = true)
 {
     int num = -1;
     if (file.ContentLength > 0)
     {
         if (file.ContentType.Contains("image"))
         {
             WebImage webImage = new WebImage(file.InputStream);
             if (webImage != null)
             {
                 string imageFormat = file.ContentType.Replace("image/", "");
                 string str = "upload_" + (object)DateTime.Now.Ticks;
                 webImage.Save(this._Path + str, imageFormat, true);
                 if (thumbnail)
                 {
                     webImage.Resize(this._ThumbHeight, this._ThumbWidth, true, false);
                     webImage.Crop(1, 1, 0, 0).Save(this._ThumbnailPath + str, imageFormat, true);
                 }
                 num = 1;
             }
         }
         else
         {
             string str = "upload_" + (object)DateTime.Now.Ticks + new FileInfo(file.FileName).Extension;
             TFile.StreamToFile(file.InputStream, this._Path + str);
         }
     }
     return num;
 }
Ejemplo n.º 8
0
        public ActionResult Thumbnail(string id)
        {
            var repository = new TagRepository();
            var tag = repository.GetTag(id);
            var photoList = repository.GetPhotoList(id);

            if (tag != null && photoList.Count > 0)
            {
                using (MultiThumbnailGenerator generator = new MultiThumbnailGenerator())
                {
                    foreach (var photo in photoList)
                    {
                        using (var imageStream = new System.IO.MemoryStream(photo.FileContents))
                        {
                            using (var image = System.Drawing.Image.FromStream(imageStream))
                            {
                                generator.AddImage(image);
                            }
                        }
                    }

                    using (var outStream = new System.IO.MemoryStream())
                    {
                        generator.WritePngToStream(outStream);
                        var image = new WebImage(outStream);
                        image.Write();
                    }
                }

                return null;
            }

            return Redirect("~/Content/Images/gallery-empty.png");
        }
Ejemplo n.º 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
                    };
            }
        }
Ejemplo n.º 10
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);
        }
Ejemplo n.º 11
0
        public string MakeThumbnail(WebImage image, int? postId, bool reachedPicLimit)
        {
            var post = _ctx.Post.Where(p => p.Id == postId).SingleOrDefault();
            image.Resize(110, 110, true, true);

            var filename = Path.GetFileName(image.FileName).Replace(" ", "");
            image.Save(Path.Combine("~/Thumbnails", filename));

            var postImage = new ImageModel
            {
                ImageUrl = ("/Thumbnails/" + filename),
                IsDeleted = false,
                Post = post,
                IsThumbnail = true

            };

            if (reachedPicLimit)
            {
                postImage.ImageUrl = "/Images/picLimit.png";
            }

            _ctx.Image.Add(postImage);
            _ctx.SaveChanges();

            return postImage.ImageUrl;
        }
Ejemplo n.º 12
0
        public ImageResult GetImage(int id, string hash, ImageHelper.ImageSize dimensions)
        {
            var image = imageService.Find(id);

            var imageSize = ImageHelper.GetDefaultImageDimensions(dimensions);

            if (image == null || image.Hash != hash)
            {
                return GetDefaultImage(dimensions);
            }

            var imageFile = ImageHelper.GetImageFilePath(image.Hash, image.CreateDate);

            if (!System.IO.File.Exists(imageFile))
            {
                return GetDefaultImage(dimensions);
            }

            Response.AppendHeader("content-disposition", "attachment; filename=" + image.Name);

            var webImage = new WebImage(imageFile);

            ImageHelper.ResizeImage(ref webImage, imageSize.Width, imageSize.Height);

            return new ImageResult {Image = webImage, ImageFormat = ImageHelper.GetImageFormat(image.Name)};
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Reference this in HTML as <img src="/Photo/WatermarkedImage/{ID}" />
        /// Simplistic example supporting only jpeg images.
        /// </summary>
        /// <param name="ID">Photo ID</param>
        public ActionResult WatermarkedImage(int id)
        {
            // Attempt to fetch the photo record from the database using Entity Framework 4.2.
            var file = FileManagerRepository.GetSingle(id);

            if (file != null) // Found the indicated photo record.
            {
                var dic = new Dictionary <String, String>();
                // Create WebImage from photo data.
                // Should have 'using System.Web.Helpers' but just to make it clear...
                String url       = String.Format("https://docs.google.com/uc?id={0}", file.GoogleImageId);
                byte[] imageData = GeneralHelper.GetImageFromUrlFromCache(url, dic);
                var    wi        = new System.Web.Helpers.WebImage(imageData);

                // Apply the watermark.
                wi.AddTextWatermark("EMIN YUCE");

                // Extract byte array.
                var image = wi.GetBytes("image/jpeg");

                // Return byte array as jpeg.
                return(File(image, "image/jpeg"));
            }
            else // Did not find a record with passed ID.
            {
                return(null); // 'Missing image' icon will display on browser.
            }
        }
Ejemplo n.º 14
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");
        }
Ejemplo n.º 15
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;
        }
Ejemplo n.º 16
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 });
            }
        }
Ejemplo n.º 17
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));
        }
        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 string SubirImagen(WebImage imagen, int dimensionMaxima)
 {
     if (imagen != null && EsUnArchivoImagen(imagen.FileName))
     {
         var nombreArchivoSubido = SubirImagen(imagen, dimensionMaxima, UrlImagenHelper.DirectorioImagenes);
         return nombreArchivoSubido;
     }
     return string.Empty;
 }
Ejemplo n.º 20
0
        public static void UploadImage(this CloudBlobContainer storageContainer, string blobName, WebImage image)
        {
            var blob = storageContainer.GetBlockBlobReference(blobName);
            blob.Properties.ContentType = "image/" + image.ImageFormat;

            using (var stream = new MemoryStream(image.GetBytes(), writable: false))
            {
                blob.UploadFromStream(stream);
            }
        }
Ejemplo n.º 21
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);
        }
Ejemplo n.º 22
0
        public static ImageResult GetDefaultImage(ImageDimensions dimensions)
        {
            HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename = default");

            var defaultImage = new WebImage("~/Content/img/default.png");

            ResizeImage(ref defaultImage, dimensions.Width, dimensions.Height);

            return new ImageResult {Image = defaultImage, ImageFormat = GetImageFormat(defaultImage.FileName)};
        }
Ejemplo n.º 23
0
        public static void FullImageSave(WebImage image)
        {
            if (image != null)
            {
                var filename = Path.GetFileName(image.FileName);
                var filepath = Path.Combine(DefaulFull, filename);
                image.Save(filepath);

            }
        }
Ejemplo n.º 24
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=\"\" />");
 }
Ejemplo n.º 25
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);
        }
        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;
        }
Ejemplo n.º 27
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);
     }
 }
Ejemplo n.º 28
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);
 }
Ejemplo n.º 29
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);
        }
Ejemplo n.º 30
0
        public FileContentResult Get(int id, string filename)
        {
            var asset = AssetService.FindById(id);
            //return Content(asset.Data.Length.ToString());

            // writes directly to the stream
            var webImage = new WebImage(asset.Data)
                //.Resize(100, 100, true, true)
                .Write(asset.MimeType)
                .GetBytes(asset.MimeType);

            return File(new byte[0], asset.MimeType);
        }
Ejemplo n.º 31
0
 public MetroTileImage(string src)
 {
     try
     {
         this.image = new WebImage(src);
         PathUri = src;
         Height = this.image.Height;
         Width = this.image.Width;
     }
     catch
     {
         // ???
     }
 }
Ejemplo n.º 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));
        }
Ejemplo n.º 33
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 }));
        }
Ejemplo n.º 34
-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);
        }