//method to display Add Picture Partial view public PartialViewResult AddPartial(int albumID) { AddPictureModel pictureModel = new AddPictureModel(); pictureModel.AlbumID = albumID; return(PartialView(pictureModel)); }
public ActionResult AddPicture(AddPictureModel picture) { if (ModelState.IsValid) { try { var pictureId = CreatePicture(picture); var user = userService.GetUserEntity(User.Identity.Name); var profile = new PictureProfileBll() { Description = picture.Description, LoadingDate = DateTime.Now, PictureId = pictureId, UserId = user.Id, }; picProfileService.CreatePictureProfile(profile); TempData["MessageType"] = MessageType.success; TempData["StrongResultMessage"] = "Фото успешно загружено"; } catch (Exception) { TempData["MessageType"] = MessageType.info; TempData["StrongResultMessage"] = "Не удалось загрузить новое фото"; } return(RedirectToAction("ShowPhotoAlbum", "PhotoAlbum")); } return(View(picture)); }
public void CreateMovie(CreateMovieModel newMovieModel, string path) { var producerIds = newMovieModel.SelectedProducersIds; var genresIds = newMovieModel.SelectedGenresIds; var actorsIds = newMovieModel.SelectedActorsIds; var newMovie = _mapper.Map <CreateMovieModel, Movie>(newMovieModel); var newPictureModel = new AddPictureModel { Url = path }; var newPicture = _mapper.Map <AddPictureModel, Picture>(newPictureModel); newMovie.Pictures.Add(newPicture); foreach (var p in _db.Producers.Where(x => producerIds.Contains(x.Id))) { newMovie.Producers.Add(p); } foreach (var g in _db.Genres.Where(x => genresIds.Contains(x.Id))) { newMovie.Genres.Add(g); } foreach (var a in _db.Actors.Where(x => actorsIds.Contains(x.Id))) { newMovie.Actors.Add(a); } _db.Movies.Add(newMovie); _db.SaveChanges(); }
public ActionResult AddPicture(AddPictureModel picture) { if (ModelState.IsValid) { try { var pictureId = CreatePicture(picture); var user = userService.GetUserEntity(User.Identity.Name); var profile = new PictureProfileBll() { Description = picture.Description, LoadingDate = DateTime.Now, PictureId = pictureId, UserId = user.Id, }; picProfileService.CreatePictureProfile(profile); TempData["MessageType"] = MessageType.success; TempData["StrongResultMessage"] = "Фото успешно загружено"; } catch (Exception) { TempData["MessageType"] = MessageType.info; TempData["StrongResultMessage"] = "Не удалось загрузить новое фото"; } return RedirectToAction("ShowPhotoAlbum", "PhotoAlbum"); } return View(picture); }
public ActionResult AddPicture(AddPictureModel model, HttpPostedFileBase file) { var user = db.User.FirstOrDefault(x => x.login == User.Identity.Name); if (user == null || !IsItMineGallery(model.galleryId)) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ViewBag.galleryId = new SelectList(user.Gallery, "id", "name"); if (file == null) { ModelState.AddModelError(string.Empty, "You must select an image."); return(View(model)); } if (file.ContentLength > 750 * 1000) { ModelState.AddModelError(string.Empty, "File size must be less than 750 kilobytes."); } string file_extention = Path.GetExtension(file.FileName).ToLower(); if (file_extention != ".mpo" && file_extention != ".jpg") { ModelState.AddModelError(string.Empty, "File extention must be '.mpo' or '.jpg'."); } if (model.isAdvanced && model.isTo2d && model.leftOrRight < 0 && model.leftOrRight > 1) { ModelState.AddModelError(string.Empty, "You must choose which of the images (left or right) should be saved in 2D."); } if (!ModelState.IsValid) { return(View(model)); } Picture picture = new Picture { description = model.description, galleryId = model.galleryId, CreationDate = DateTime.Now }; db.Picture.Add(picture); db.SaveChanges(); picture = new PictureSaver(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Picture")).AnalyzeAndSave(picture, model, file); picture.Gallery.LastPicture = picture; db.Entry(picture).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Details", "Gallery", new { id = picture.galleryId })); }
/// <summary> /// Saves data about the picture to the DB /// </summary> /// <param name="addPictureModel"></param> /// <param name="imageFileName"></param> /// <returns></returns> private bool SavePicture(AddPictureModel addPictureModel, string fileNameWithoutExt) { var pictureModel = new PictureModel { AlbumID = addPictureModel.AlbumID, PictureTitle = addPictureModel.Title, FileName = fileNameWithoutExt, FilePath = $"~/Pictures/{fileNameWithoutExt}.png", FileSize = addPictureModel.PictureFile.ContentLength, }; return(_pictureManager.AddPicture(pictureModel, addPictureModel.AlbumID)); }
public ActionResult AddPicture(short?id) { if (id == null || !IsItMine(id)) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } AddPictureModel picture = new AddPictureModel { Gallery = db.Gallery.Find(id) }; return(View(picture)); }
public async Task <IActionResult> AddPicture(AddPictureModel model) { if (!ModelState.IsValid) { this.TempData.AddErrorMessage("Please fill out the form correctly."); return(View()); } User user = await this.userManager.FindByEmailAsync(this.User.Identity.Name); await this.pictureService.CreatePicture(user.Id, model.Picture); this.TempData.AddSuccessMessage("Picture added successfully."); return(RedirectToAction("Details", "Profiles", new { id = user.Id })); }
public ActionResult AddPicture(int entityId, string entityName) { if (!_customerSettings.AllowViewingProfiles) { return(RedirectToRoute("HomePage")); } var addPictureModel = new AddPictureModel() { EntityId = entityId, EntityName = entityName, DisplayOrder = 1 }; return(View("mobSocial/BusinessPage/AddPicture", addPictureModel)); }
private int CreatePicture(AddPictureModel picture) { var imageBytes = picture.ImageFile.GetBytes(); var newPicture = new PictureBll() { Name = picture.Name, Image = imageBytes, Hash = GetImageHash(imageBytes), }; pictureService.CreatePicture(newPicture); PictureBll addedPic = pictureService .GetPicturesByHash(newPicture.Hash) .First(pic => pic.Name == picture.Name); return(addedPic.Id); }
public ActionResult Index(AddPictureModel addPictureModel) { if (ModelState.IsValid) { //ImageFile imageFile = new ImageFile(addPictureModel.PictureFile); //imageFile.ServerFileName = Server.MapPath($"~/Pictures/{imageFile.ImageFieNameWithExt}"); //imageFile.PerformUpload(); //get the full path of the file to be uploaded var fileName = addPictureModel.PictureFile.FileName; //get the image name from the fileName sent by the browser without its extension var imageFileName = Path.GetFileNameWithoutExtension(fileName); //get the file extension var fileExtension = Path.GetExtension(fileName); //validate the extention by comparing it with the allowed extensions var isValidExtension = ".jpg,.png,.jpeg,.JPG,.PNG,.JPEG".Split(',').Contains(fileExtension); //if extension is a valid image, copy to output stream and save copied file path to database if (isValidExtension) { //create image processor var imageProcessor = new ImageService(); //scale picture retaining a max aspect ratio of 400px var imageInputStream = imageProcessor.ScaleWidth(addPictureModel.PictureFile.InputStream, 400); //get the name of the image with our new extension var imageFileNameWithExt = $"{imageFileName}.png"; //get the file path we want to upload to var filePath = Server.MapPath($"~/Pictures/{imageFileNameWithExt}"); //open an output stream for saving file using (var outputStream = System.IO.File.Create(filePath)) { //copy image to the output stream imageInputStream.CopyTo(outputStream); } //Save picture in DB var isSaved = SavePicture(addPictureModel, imageFileName); if (isSaved) { //if saving to DB is successful redirect to index in order to load picture and display success msg TempData[Alert.AlertMsgKey] = "Picture Uploaded Successfully"; TempData[Alert.AlertTypeKey] = Alert.AlertSuccess; return(RedirectToAction("Index", "Picture", new { albumID = addPictureModel.AlbumID, alert = true })); } } else { TempData[Alert.AlertMsgKey] = "Error!!!...Picture must be jpeg, jpg or png"; TempData[Alert.AlertTypeKey] = Alert.AlertDanger; return(RedirectToAction("Index", "Picture", new { albumID = addPictureModel.AlbumID, alert = true })); } } //if ModelState is invalid or saving picture to DB fails TempData[Alert.AlertMsgKey] = "Ooops!!!...Couldn't save picture"; TempData[Alert.AlertTypeKey] = Alert.AlertDanger; return(RedirectToAction("Index", "Picture", new { albumID = addPictureModel.AlbumID, alert = true })); }
public async System.Threading.Tasks.Task <bool> UploadPictureAsync(Stream pictureStream, string contentType, AddPictureModel additionalInfo) { var builder = new UriBuilder(AppSettings.PlantsEndpoint); builder.AppendToPath("api"); builder.AppendToPath("plants"); await requestService.PostAsync(builder.ToString(), new { ImageBase64 = pictureStream.ConvertToBase64(), ContentType = contentType, additionalInfo.Latitude, additionalInfo.Longitude, additionalInfo.Name, additionalInfo.DeviceId, additionalInfo.EndangeredLevel, additionalInfo.Family, additionalInfo.ScientificName, additionalInfo.Surrounding, additionalInfo.Description }); return(true); }
public ActionResult AddPicture(int entityId, string entityName) { if (!_customerSettings.AllowViewingProfiles) { return RedirectToRoute("HomePage"); } var addPictureModel = new AddPictureModel() { EntityId = entityId, EntityName = entityName, DisplayOrder = 1 }; return View(ControllerUtil.MobSocialViewsFolder + "/BusinessPage/AddPicture.cshtml", addPictureModel); }
public Picture AnalyzeAndSave(Picture picture, AddPictureModel model, HttpPostedFileBase file) { // зберігаю зображення string picture_name = picture.id.ToString() + Path.GetExtension(file.FileName); string picture_folder_name = Path.Combine(picture_folder, picture_name); file.SaveAs(picture_folder_name); picture.path = Path.Combine("Picture", picture_name); // записую відносний шлях в обєкт бази даних // отримую всі зображення з файлу var images = MpoParser.GetImageSources(picture_folder_name); Image img_for_thumb; if (!images.Any()) // якщо 2D { img_for_thumb = Image.FromFile(picture_folder_name); picture.type = "2D"; } else // якщо 3D { if (model.isAdvanced && model.isTo2d) // якщо юзер хоче зберегти 3D зображення в 2D { img_for_thumb = images.ElementAt(model.leftOrRight); picture_name = Path.ChangeExtension(picture_name, ".JPG"); picture.type = "2D"; System.IO.File.Delete(picture_folder_name); // видаляю непотрібний файл } else { img_for_thumb = images.ElementAt(0); // беру перше зображення (з лівої камери) // змінюю формат оригіналу на .mpo (на сервер заавжди приходить зображення формату JPG) picture_name = Path.ChangeExtension(picture_name, ".MPO"); file.SaveAs(Path.Combine(picture_folder, picture_name)); picture.type = "3D"; } img_for_thumb.Save(Path.ChangeExtension(picture_folder_name, ".JPG")); // зберігаю зображення, з якого буду робити прев'ю picture.path = Path.Combine("Picture", picture_name); } var original_length = PictureTools.GetByteSize(img_for_thumb).LongLength; // створюю прев'ю var thumb_sm = PictureTools.MakeThumbnail(img_for_thumb, 155, 97); var thumb_sm_length = PictureTools.GetByteSize(thumb_sm).LongLength; if (original_length > thumb_sm_length) { thumb_sm.Save($"{picture_folder}/{picture.id}-thumb_sm.JPG"); } var thumb_md = PictureTools.MakeThumbnail(img_for_thumb, 280, 999); var thumb_md_length = PictureTools.GetByteSize(thumb_md).LongLength; if (original_length > thumb_md_length) { thumb_md.Save($"{picture_folder}/{picture.id}-thumb_md.JPG"); if (Path.GetExtension(picture.path) == ".MPO") { System.IO.File.Delete(picture_folder_name); // видаляю непотрібний файл } } return(picture); }
private int CreatePicture(AddPictureModel picture) { var imageBytes = picture.ImageFile.GetBytes(); var newPicture = new PictureBll() { Name = picture.Name, Image = imageBytes, Hash = GetImageHash(imageBytes), }; pictureService.CreatePicture(newPicture); PictureBll addedPic = pictureService .GetPicturesByHash(newPicture.Hash) .First(pic => pic.Name == picture.Name); return addedPic.Id; }