public string UploadResize(int x, int y, string dir, HttpPostedFileBase file) { /* Para o uso dessa função é preciso adicionar o imageresizer que se encontra na seguinte URL: http://imageresizing.net/ Para o funcionamento, voce deve passar como parametro (Largura, Altura, Diretorio onde vai ser salvo, arquivo) by: twitter: @DashTail facebook: /faelbcabral git: /rafacabral */ var fileName = file.FileName; if (file != null && file.ContentLength > 0) { String FileExtn = System.IO.Path.GetExtension(file.FileName).ToLower(); if (!(FileExtn == ".jpg" || FileExtn == ".png" || FileExtn == ".gif")) { //@ViewBag.error = "msg de erro"; } else { ImageResizer.ImageJob i = new ImageResizer.ImageJob(file, dir + "" + fileName, new ImageResizer.ResizeSettings( "width=" + x + ";height=" + y + ";format=jpg;mode=max")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); } } return fileName; }
public async Task<IActionResult> Create(IFormFile croppedImage1, IFormFile croppedImage2, int distance) { var uploads = Path.Combine(_environment.WebRootPath, "Uploads"); if (croppedImage1.Length > 0 && croppedImage2.Length > 0) { var puzzleImageId = Guid.NewGuid().ToString(); var fileName = string.Format("{0}.jpg", puzzleImageId); await croppedImage1.SaveAsAsync(Path.Combine(uploads, fileName)); ImageResizer.ImageJob img1 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "16-9", "400", fileName), new ImageResizer.Instructions("maxheight=400;&scale=both;format=jpg;mode=max")); img1.Build(); ImageResizer.ImageJob img2 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "16-9", "1065", fileName), new ImageResizer.Instructions("maxheight=1065;&scale=both;format=jpg;mode=max")); img2.Build(); if (ModelState.IsValid) { await _puzzleRepository.AddPuzzleAsync(User, puzzleImageId, distance, _shopRepository.GetUserShop(User).ID); } } return View(); }
public static List<string> UploadAndRename(HttpPostedFileBase file) { const string uploadFolder = "~/Uploads/"; if (file == null || file.ContentLength <= 0) throw new Exception("Image error: File is null or has no content."); var generatedFiles = new List<string>(); var versions = new Dictionary<string, string> { {"_s", "width=160&height=160&crop=auto&format=jpg"}, {"_x", "maxwidth=1280&maxheight=1280&format=jpg"} }; // Generate a filename (GUIDs are best). var fileName = Path.Combine(uploadFolder, Guid.NewGuid().ToString()); // Generate each version foreach (string suffix in versions.Keys) { // Let the image builder add the correct extension based on the output file type var imageJob = new ImageResizer.ImageJob(file, fileName + suffix + ".<ext>", new ImageResizer.Instructions(versions[suffix])); imageJob.Build(); generatedFiles.Add(fileName.Replace(uploadFolder, "") + suffix + ".jpg"); } return generatedFiles; }
public static void OptimizeImage(HttpPostedFileBase file, int maxWidth, int maxHeight, string outputPath, int quality = 70) { ImageResizer.ImageJob newImage = new ImageResizer.ImageJob(file, outputPath, new ImageResizer.Instructions("maxwidth=" + maxWidth + ";maxheight=" + maxHeight + ";quality=" + quality)); newImage.Build(); }
public HttpResponseMessage Get(string id, string type) { string orig = HttpContext.Current.Server.MapPath("~/snaps/orig/"); string root = HttpContext.Current.Server.MapPath("~/snaps/" + type + "/"); var path = root + id; var orig_path = orig + id; HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); if (File.Exists(path) == false) { // try regenerating it if the original file exists if(File.Exists(orig_path) == true) { FileInfo fileInfo = new FileInfo(orig_path); // generate 640px version (retina display) string sz640_dir = HttpContext.Current.Server.MapPath("~/snaps/640/"); string filename = sz640_dir + id; ImageResizer.ImageJob i = new ImageResizer.ImageJob(orig_path, filename, new ImageResizer.Instructions( "width=640;height=900;format=jpg;mode=max;autorotate=true")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); // generate a 500px version string sz500_dir = HttpContext.Current.Server.MapPath("~/snaps/500/"); filename = sz500_dir + id; i = new ImageResizer.ImageJob(orig_path, filename, new ImageResizer.Instructions( "width=500;height=900;format=jpg;mode=max;autorotate=true")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); // generate thumb version string thumb_dir = HttpContext.Current.Server.MapPath("~/snaps/thumb/"); filename = thumb_dir + id; i = new ImageResizer.ImageJob(orig_path, filename, new ImageResizer.Instructions( "width=75;height=75;format=jpg;mode=max;autorotate=true")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); } else { // doesn't exist.. so... do nothing return new HttpResponseMessage(); } } var stream = new FileStream(path, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); result.StatusCode = HttpStatusCode.OK; return result; }
public static Models.Picture ReadPicture(HttpPostedFileBase upload) { if (upload == null) { return(null); } var avatar = new Models.Picture { FileName = System.IO.Path.GetFileName(upload.FileName), PictureType = Models.PictureType.Avatar, ContentType = upload.ContentType }; HttpPostedFileBase uploadforMini = upload; //make small upload.InputStream.Seek(0, 0); using (var stream = new System.IO.MemoryStream()) { ImageResizer.ImageJob image = new ImageResizer.ImageJob(upload, stream, new ImageResizer.Instructions("width=200;height=200;crop=auto;format=jpg;anchor=middlecenter;autorotate=true;quality=100")); image.Build(); System.Drawing.Image Image = System.Drawing.Image.FromStream(stream); System.IO.MemoryStream ms = new System.IO.MemoryStream(); Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); avatar.Content = ms.ToArray(); //make smaller uploadforMini.InputStream.Seek(0, 0); using (var streamMini = new System.IO.MemoryStream()) { ImageResizer.ImageJob imageMini = new ImageResizer.ImageJob(uploadforMini, streamMini, new ImageResizer.Instructions("width=50;height=50;crop=auto;format=jpg;anchor=middlecenter;autorotate=true;quality=100")); imageMini.Build(); System.Drawing.Image ImageMini = System.Drawing.Image.FromStream(streamMini); System.IO.MemoryStream msMini = new System.IO.MemoryStream(); ImageMini.Save(msMini, System.Drawing.Imaging.ImageFormat.Jpeg); avatar.ContentMini = msMini.ToArray(); return(avatar); //} } } //return null; }
public ActionResult Create([Bind(Include = "SitesetId,Phone,Address,Email,ImageUrl,FbId,TwitterId,GoogleId,InstagramId,LinkedinId,Copyright,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy,DelFlg")] Siteset siteset, HttpPostedFileBase ImageUrl) { if (ModelState.IsValid) { db.Entry(siteset).State = EntityState.Added; siteset.CreatedBy = User.Identity.GetUserId(); siteset.CreatedDate = DateTime.Now; if (ImageUrl != null) { string pathToCreate = "~/Images/siteset"; if (!Directory.Exists(Server.MapPath(pathToCreate))) { //Now you know it is ok, create it Directory.CreateDirectory(Server.MapPath(pathToCreate)); } string extension = Path.GetExtension(ImageUrl.FileName); string fileName = Path.GetFileNameWithoutExtension(ImageUrl.FileName); string id = Guid.NewGuid().ToString(); string imageUrl = "/Images/siteset/" + fileName + "" + /*main.MainId.ToString()*/ id + extension; ImageUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension)); string DestinationPath = Path.Combine(Server.MapPath(pathToCreate)); DestinationPath += "\\" + fileName + id; ImageResizer.ImageJob i = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_thumb.jpg", new ImageResizer.ResizeSettings( "width=200;height=200;format=jpg;mode=max")); i.Build(); siteset.ImageUrl = imageUrl; db.Sitesets.Add(siteset); } else { db.Sitesets.Add(siteset); db.SaveChanges(); return(RedirectToAction("Index")); } db.SaveChanges(); return(RedirectToAction("Index")); } return(View(siteset)); }
public ActionResult Create([Bind(Include = "PastExComMemberId,Name,Position,ImageUrl,Year,Linkedin,Facebook,Email,Mobile,Landline,Address,DOB,UniqueId,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy,DelFlg")] PastExComMember pastExComMember, HttpPostedFileBase ImageUrl) { if (ModelState.IsValid) { db.Entry(pastExComMember).State = EntityState.Added; pastExComMember.CreatedBy = User.Identity.GetUserId(); pastExComMember.CreatedDate = DateTime.Now; if (ImageUrl != null) { string pathToCreate = "~/Images/pastExComMember"; if (!Directory.Exists(Server.MapPath(pathToCreate))) { //Now you know it is ok, create it Directory.CreateDirectory(Server.MapPath(pathToCreate)); } string extension = Path.GetExtension(ImageUrl.FileName); string fileName = Path.GetFileNameWithoutExtension(ImageUrl.FileName); string id = Guid.NewGuid().ToString(); string imageUrl = "/Images/pastExComMember/" + fileName + "" + /*main.MainId.ToString()*/ id + extension; ImageUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension)); string DestinationPath = Path.Combine(Server.MapPath(pathToCreate)); DestinationPath += "\\" + fileName + id; ImageResizer.ImageJob i = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_thumb.jpg", new ImageResizer.ResizeSettings( "width=200;height=200;format=jpg;mode=max")); i.Build(); pastExComMember.ImageUrl = imageUrl; db.PastExComMembers.Add(pastExComMember); } else { db.PastExComMembers.Add(pastExComMember); db.SaveChanges(); return(RedirectToAction("Index")); } db.SaveChanges(); return(RedirectToAction("Index")); } return(View(pastExComMember)); }
public ActionResult Create([Bind(Include = "MainsponsorId,ImageUrl,Title,Phone,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy,DelFlg")] Mainsponsor mainsponsor, HttpPostedFileBase ImageUrl) { if (ModelState.IsValid) { db.Entry(mainsponsor).State = EntityState.Added; mainsponsor.CreatedBy = User.Identity.GetUserId(); mainsponsor.CreatedDate = DateTime.Now; if (ImageUrl != null) { string pathToCreate = "~/Images/mainsponsor"; if (!Directory.Exists(Server.MapPath(pathToCreate))) { //Now you know it is ok, create it Directory.CreateDirectory(Server.MapPath(pathToCreate)); } string extension = Path.GetExtension(ImageUrl.FileName); string fileName = Path.GetFileNameWithoutExtension(ImageUrl.FileName); string id = Guid.NewGuid().ToString(); string imageUrl = "/Images/mainsponsor/" + fileName + "" + /*main.MainId.ToString()*/ id + extension; ImageUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension)); string DestinationPath = Path.Combine(Server.MapPath(pathToCreate)); DestinationPath += "\\" + fileName + id; ImageResizer.ImageJob i = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_thumb.jpg", new ImageResizer.ResizeSettings( "width=308;height=270;format=jpg;mode=max")); i.Build(); mainsponsor.ImageUrl = imageUrl; db.Mainsponsors.Add(mainsponsor); } else { db.Mainsponsors.Add(mainsponsor); db.SaveChanges(); return(RedirectToAction("Index")); } db.SaveChanges(); return(RedirectToAction("Index")); } return(View(mainsponsor)); }
public HttpResponseMessage Post() { Photo newPhoto = new Photo(); // Loop through each uploaded file foreach (string fileKey in HttpContext.Current.Request.Files.Keys) { HttpPostedFile file = HttpContext.Current.Request.Files[fileKey]; // Skip unused file controls. if (file.ContentLength <= 0) continue; string guid = Guid.NewGuid().ToString(); string fileName = guid + fileExtension; string src = hostName + hostContainer + "/" + fileName; // Add filename to srcList newPhoto = new Photo { Id = guid, DateTimeCreated = new DateTimeOffset(DateTime.UtcNow), Source = src, Width = photoWidth }; // Retrieve reference to the blob we want to create CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileName); // Populate our blob with contents from the uploaded file. using (var ms = new MemoryStream()) { ImageResizer.ImageJob i = new ImageResizer.ImageJob(file.InputStream, ms, new ImageResizer.ResizeSettings("width=" + photoWidth + ";format=" + fileExtension)); i.Build(); blockBlob.Properties.ContentType = contentType; ms.Seek(0, SeekOrigin.Begin); blockBlob.UploadFromStream(ms); } } return Request.CreateResponse(HttpStatusCode.Created, newPhoto); }
public IActionResult Create(IFormFile croppedImage1, string shortDesc, string longDesc, decimal originalPrice, decimal discountPrice) { //Save image var uploads = Path.Combine(_environment.WebRootPath, "Uploads"); if (croppedImage1.Length > 0) { var prizeImageId = Guid.NewGuid().ToString(); var fileName = string.Format("{0}.jpg", prizeImageId); croppedImage1.SaveAs(Path.Combine(uploads, fileName)); ImageResizer.ImageJob img1 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "Prizes", "400", fileName), new ImageResizer.Instructions("maxheight=400;&scale=both;format=jpg;mode=max")); img1.Build(); ImageResizer.ImageJob img2 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "Prizes", "600", fileName), new ImageResizer.Instructions("maxheight=600;&scale=both;format=jpg;mode=max")); img2.Build(); Prize newPrize = new Prize(); newPrize.PrizeImage = prizeImageId; newPrize.ShortDesc = shortDesc; newPrize.LongDesc = longDesc; newPrize.OriginalPrice = originalPrice; newPrize.DiscountPrice = discountPrice; newPrize.ShopId = 2; newPrize.Status = (int)EnumHelper.PrizeStatus.InProduction; if (ModelState.IsValid) { _context.Prize.Add(newPrize); _context.SaveChanges(); } } return(View()); }
public IActionResult Create(IFormFile croppedImage1, string shortDesc, string longDesc, decimal originalPrice, decimal discountPrice) { //Save image var uploads = Path.Combine(_environment.WebRootPath, "Uploads"); if (croppedImage1.Length > 0) { var prizeImageId = Guid.NewGuid().ToString(); var fileName = string.Format("{0}.jpg", prizeImageId); croppedImage1.SaveAs(Path.Combine(uploads, fileName)); ImageResizer.ImageJob img1 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "Prizes", "400", fileName), new ImageResizer.Instructions("maxheight=400;&scale=both;format=jpg;mode=max")); img1.Build(); ImageResizer.ImageJob img2 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "Prizes", "600", fileName), new ImageResizer.Instructions("maxheight=600;&scale=both;format=jpg;mode=max")); img2.Build(); Prize newPrize = new Prize(); newPrize.PrizeImage = prizeImageId; newPrize.ShortDesc = shortDesc; newPrize.LongDesc = longDesc; newPrize.OriginalPrice = originalPrice; newPrize.DiscountPrice = discountPrice; newPrize.ShopId = 2; newPrize.Status = (int)EnumHelper.PrizeStatus.InProduction; if (ModelState.IsValid) { _context.Prize.Add(newPrize); _context.SaveChanges(); } } return View(); }
public byte[] ProcessPicture(HttpPostedFileBase upload) { if (upload == null) { return(null); } upload.InputStream.Seek(0, 0); System.IO.Stream stream = new System.IO.MemoryStream(); ImageResizer.ImageJob image = new ImageResizer.ImageJob(upload, stream, new ImageResizer.Instructions("width=50;height=50;crop=auto;format=jpg;anchor=middlecenter;autorotate=true;quality=100")); image.Build(); System.Drawing.Image Image = System.Drawing.Image.FromStream(stream); System.IO.MemoryStream ms = new System.IO.MemoryStream(); Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return(ms.ToArray()); }
public ActionResult Edit([Bind(Include = "EventId,Title,LinkUrl,ImageUrl,EventDate,Description,Phone,Timing,Address,IsCompleted,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy,DelFlg")] Event @event, HttpPostedFileBase ImageUrl) { if (ModelState.IsValid) { db.Entry(@event).State = EntityState.Modified; @event.ModifiedBy = User.Identity.GetUserId(); @event.ModifiedDate = DateTime.Now; if (ImageUrl != null) { string pathToCreate = "~/Images/@event"; if (!Directory.Exists(Server.MapPath(pathToCreate))) { //Now you know it is ok, create it Directory.CreateDirectory(Server.MapPath(pathToCreate)); } string extension = Path.GetExtension(ImageUrl.FileName); string fileName = Path.GetFileNameWithoutExtension(ImageUrl.FileName); string id = Guid.NewGuid().ToString(); string imageUrl = "/Images/@event/" + fileName + "" + /*main.MainId.ToString()*/ id + extension; ImageUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension)); string DestinationPath = Path.Combine(Server.MapPath(pathToCreate)); DestinationPath += "\\" + fileName + id; ImageResizer.ImageJob i = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_thumb.jpg", new ImageResizer.ResizeSettings( "width=200;height=200;format=jpg;mode=max")); i.Build(); ImageResizer.ImageJob j = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_list.jpg", new ImageResizer.ResizeSettings( "width=500;height=250;format=jpg;mode=crop")); j.Build(); @event.ImageUrl = imageUrl; } db.SaveChanges(); return(RedirectToAction("Index")); } return(View(@event)); }
public Guid ManageNewsUpdateAndCreate(ManageNewsModel manageNewsModel) { Content content; //var item1 = content.Content_Languages.Where(z => z.Title == manageNewsModel.Title); if (manageNewsModel.ID == Guid.Empty)//New { content = new Content(); manageNewsModel.ID = content.ID; content.Content_Languages = new List <Content_Language>(); //----------- Duplicate Check ---- if (content.Content_Languages.Where(z => z.Title == manageNewsModel.Title).Count() > 0) { string a = manageNewsModel.Title; } //----------- Duplicate Check ---- content.CreatedBy = TSM.Model.TSMContext.CurrentUser.ID; content.CreatedDate = DateTime.UtcNow; content.ContentDate = manageNewsModel.ContentDate.Value.Date; //content.RecordID = manageNewsModel.RecordId; //content.RegionID = manageNewsModel.RegionID; //content.CountryID = manageNewsModel.CountryID; content.HrefLink = manageNewsModel.HrefLink; if (manageNewsModel.File != null) { string fileName = DateTime.Now.Ticks.ToString() + "_" + manageNewsModel.File.FileName; string path = System.IO.Path.Combine( HttpContext.Current.Server.MapPath("~/UploadedImages/NewsImages/"), fileName); var instruction = new ImageResizer.Instructions(); instruction.Width = 500; instruction.Height = 500; instruction.Mode = ImageResizer.FitMode.Max; instruction.JpegQuality = 80; ImageResizer.ImageJob imageJob = new ImageResizer.ImageJob(manageNewsModel.File, fileName, instruction); try { imageJob.Build(); } catch { } manageNewsModel.File.SaveAs(path); manageNewsModel.ImagePath = "/UploadedImages/NewsImages/" + fileName; } } else//update { if (manageNewsModel.File != null) { string fileName = DateTime.Now.Ticks.ToString() + "_" + manageNewsModel.File.FileName; string path = System.IO.Path.Combine( HttpContext.Current.Server.MapPath("~/UploadedImages/NewsImages/"), fileName); var instruction = new ImageResizer.Instructions(); instruction.Width = 500; instruction.Height = 500; instruction.Mode = ImageResizer.FitMode.Max; instruction.JpegQuality = 80; ImageResizer.ImageJob imageJob = new ImageResizer.ImageJob(manageNewsModel.File, fileName, instruction); try { imageJob.Build(); } catch { } manageNewsModel.File.SaveAs(path); manageNewsModel.ImagePath = "/UploadedImages/NewsImages/" + fileName; } manageNewsModel.GetNewsContent(manageNewsModel.ID); content = manageNewsModel.NewsContent; content.ContentDate = manageNewsModel.ContentDate.Value.Date; content.LastModifiedBy = TSM.Model.TSMContext.CurrentUser.ID; content.LastModifiedDate = DateTime.UtcNow; //content.Image = manageNewsModel.ImagePath; } //content.ID= new Guid(); content.IsPublic = false; content.Type = ContentType.News; content.Image = manageNewsModel.ImagePath; //content.RecordID = manageNewsModel.RecordId; //content.RegionID = manageNewsModel.RegionID; //content.CountryID = manageNewsModel.CountryID; content.HrefLink = manageNewsModel.HrefLink; if (content.Content_Languages.Count <= 0) // New { content.Content_Languages.Add(new Content_Language { LanguageID = manageNewsModel.LanguageID, Content = content, SubTitle = manageNewsModel.SubTitle, Summary = manageNewsModel.Summary, Description = manageNewsModel.Description, Title = manageNewsModel.Title }); } else//Update { if (content.Content_Languages.Where(z => z.LanguageID == manageNewsModel.LanguageID).Count() > 0)//Update content with current lang id { foreach (var item in content.Content_Languages.Where(z => z.LanguageID == manageNewsModel.LanguageID)) { item.LanguageID = manageNewsModel.LanguageID; item.Content = content; item.SubTitle = manageNewsModel.SubTitle; item.Summary = manageNewsModel.Summary; item.Description = manageNewsModel.Description; item.Title = manageNewsModel.Title; break; } } else //No content is present with current lang id { content.Content_Languages.Add(new Content_Language { LanguageID = manageNewsModel.LanguageID, Content = content, SubTitle = manageNewsModel.SubTitle, Summary = manageNewsModel.Summary, Description = manageNewsModel.Description, Title = manageNewsModel.Title }); } } content.IsActive = true;//always active when new created or updated manageNewsModel.ID = content.ID; NewsService.Save(content); return(content.ID); }
public ActionResult Create([Bind(Include = "EventId,Title,LinkUrl,ImageUrl,EventDate,Description,Phone,Timing,Address,IsCompleted,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy,DelFlg")] Event @event, HttpPostedFileBase ImageUrl, HttpPostedFileBase LinkUrl) { if (ModelState.IsValid) { db.Entry(@event).State = EntityState.Added; @event.CreatedBy = User.Identity.GetUserId(); @event.CreatedDate = DateTime.Now; if (ImageUrl != null) { string pathToCreate = "~/Images/@event"; if (!Directory.Exists(Server.MapPath(pathToCreate))) { //Now you know it is ok, create it Directory.CreateDirectory(Server.MapPath(pathToCreate)); } string extension = Path.GetExtension(ImageUrl.FileName); string fileName = Path.GetFileNameWithoutExtension(ImageUrl.FileName); string id = Guid.NewGuid().ToString(); string imageUrl = "/Images/@event/" + fileName + "" + /*main.MainId.ToString()*/ id + extension; ImageUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension)); string DestinationPath = Path.Combine(Server.MapPath(pathToCreate)); DestinationPath += "\\" + fileName + id; ImageResizer.ImageJob i = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_thumb.jpg", new ImageResizer.ResizeSettings( "width=200;height=200;format=jpg;mode=max")); i.Build(); @event.ImageUrl = imageUrl; db.Events.Add(@event); } else if (LinkUrl != null && LinkUrl.ContentLength > 0) { string pathToCreate = "~/UploadedDocuments/Events"; if (!Directory.Exists(Server.MapPath(pathToCreate))) { //Now you know it is ok, create it Directory.CreateDirectory(Server.MapPath(pathToCreate)); } string extension = Path.GetExtension(LinkUrl.FileName); string fileName = Path.GetFileNameWithoutExtension(LinkUrl.FileName); string id = Guid.NewGuid().ToString(); string linkurl = "/UploadedDocuments/Events/" + fileName + "" + /*main.MainId.ToString()*/ id + extension; LinkUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension)); // extract only the filename string DestinationPath = Path.Combine(Server.MapPath(pathToCreate)); DestinationPath += "\\" + fileName + id; // store the file inside ~/App_Data/uploads folder @event.LinkUrl = linkurl; db.Events.Add(@event); } else { db.Events.Add(@event); db.SaveChanges(); return(RedirectToAction("Index")); } db.SaveChanges(); return(RedirectToAction("Index")); } return(View(@event)); }
private void ResizeImage(string originalPath, string destinationPath) { PointInCode("DrinkViewModel: ResizeImage"); //Crop to square format ImageResizer.ImageJob i = new ImageResizer.ImageJob(originalPath, destinationPath, new ImageResizer.ResizeSettings( "height=200;format=png;mode=max;")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); Uri assets = new Uri(BeursfuifPaths.AssetsPath); Uri image = new Uri(destinationPath); NewEditDrink.ImageString = assets.MakeRelativeUri(image).ToString(); }
public async System.Threading.Tasks.Task <HttpResponseMessage> PostFileAsync() { var response = new HttpResponseMessage(); var result = await Request.Content.ReadAsMultipartAsync(); var isExif = await result.Contents[1].ReadAsStringAsync(); var xCord = await result.Contents[2].ReadAsStringAsync(); var yCord = await result.Contents[3].ReadAsStringAsync(); var filter = await result.Contents[4].ReadAsStringAsync(); var description = await result.Contents[5].ReadAsStringAsync(); var accessToken = await result.Contents[6].ReadAsStringAsync(); MySession token = new MySession(accessToken); if (AccessToken.CheckAccessToken(token).StatusCode != HttpStatusCode.BadRequest) { string username = AccessToken.searchUserByAccessToken(token.AccessToken); var httpRequest = HttpContext.Current.Request; foreach (string file in httpRequest.Files) { //// get file extension var postedFile = httpRequest.Files[file]; // Get http request for POST string fileString = postedFile.FileName.ToString(); // get photo name to extract extension string fileExts = Path.GetExtension(fileString); // extract file extension (png, jpg, ect...) string ID = generateID(); // generate random ID for each photo response.StatusCode = HttpStatusCode.OK; //// save file with new ID string localfilepath = HttpContext.Current.Server.MapPath("~//photos//" + ID + fileExts); postedFile.SaveAs(localfilepath); //// save thumbnail with new ID string thumbnailFilepath = HttpContext.Current.Server.MapPath("~//photos//" + "thumbnail_" + ID + fileExts); ImageResizer.ImageJob i = new ImageResizer.ImageJob(postedFile, thumbnailFilepath, new ImageResizer.Instructions("width=100;height=100;format=jpg;mode=max;autorotate=true")); i.Build(); int manualGPS = 0; if (isExif != "true") { imageYellowBorder(ID); manualGPS = 1; } savePhotoInServer(ID, username, fileExts, manualGPS, Double.Parse(xCord), Double.Parse(yCord), filter, description); } return(response); } //else response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent("Please login to upload photos"); return(response); }
public async Task<ActionResult> AddPicture(UtilityBuildingModel model) { //ModelState.Clear(); if (model.Id == 0) { ModelState.AddModelError(model.GetPropertyName(() => model.PhotoFile), "hotel missing"); } if (model.PhotoFile == null) { ModelState.AddModelError(model.GetPropertyName(() => model.PhotoFile), "image missing"); } // take just PhotoFile validation var errors = ModelState.Where(s => s.Key != model.GetPropertyName(() => model.PhotoFile)); errors.ToList().ForEach(e => ModelState.Remove(e.Key)); if (!ModelState.IsValid) { return PartialView("_BuildingPhotoes", model); } using (var db = new Models.OnLeaveContext()) { // add pictures //var resizedImage = ImageResizer.ImageBuilder.Current.Build(buffer, rSetting); //resizedImage.Save(@"C:\\Temp\" + Path.GetFileName(model.PhotoFile.FileName)); int count = db.UtilityBuildingPhotoDetails.Count(pDetail => pDetail.UtilityBuildingId == model.Id); if (count >= 7 - 1) { return new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden, "maximum number picture exceeded"); } using (var ms = new MemoryStream()) { var job = new ImageResizer.ImageJob( model.PhotoFile, ms, new ImageResizer.Instructions("mode=crop;format=jpg;width=600;height=472;")); await Task.Run(() => job.Build()); var imageDb = new Photo { KeyWords = null, Name = Path.GetFileName(model.PhotoFile.FileName), Image = ms.ToArray() }; db.Photos.Add(imageDb); var imageDetail = new UtilityBuildingPhotoDetail { UtilityBuildingId = model.Id, KeyWords = null, PhotoId = imageDb.PhotoId }; db.UtilityBuildingPhotoDetails.Add(imageDetail); try { db.SaveChanges(); } catch (Exception ex) { System.Console.WriteLine(ex); } // get images model.PhotoIds = db.UtilityBuildingPhotoDetails .Where(pDetail => pDetail.UtilityBuildingId == model.Id) .Select(pDetail => pDetail.PhotoId) .ToList(); } } return PartialView("_BuildingPhotoes", model); }
public virtual ActionResult Upload(HttpPostedFileBase image, string imageUrl) { try { var i = new ImageResizer.ImageJob(image ?? (object) imageUrl, "~/Content/Temp/<guid>.<ext>", new ImageResizer.ResizeSettings( string.Format("width={0};height={0};mode=max", MaxDimension))) {AllowDestinationPathVariables = true}; i.Build(); var sitePath = Server.MapPath(@"~"); var relativePath = i.FinalPath.Replace(sitePath, @"~/"); var url = ResolveServerUrl(VirtualPathUtility.ToAbsolute(relativePath), false); // System.IO.File.Delete(i.FinalPath); return Json(new { success = true, imageUrl = url }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new { success = false, error = ex.Message }, "text/html", JsonRequestBehavior.AllowGet); } }