public IActionResult Upload([FromForm] UploadImageModel model) { if (!ModelState.IsValid) { return(BadRequest(new { message = "Required parameters are missing" })); } if (!CheckIfImageFile(model.File)) { return(BadRequest(new { message = "Invalid file extension" })); } var fileName = DateTime.Now.Ticks + model.Extension; var extension = "." + model.File.FileName.Split('.')[model.File.FileName.Split('.').Length - 1]; var contentType = Helper.GetFileContentType(extension); var data = _cache.Get(model.ToString()); if (data == null) { var processedImage = ProcessImage(model, fileName); return(Ok(File(processedImage, contentType, fileName))); } return(Ok(File(data, contentType, fileName))); }
private byte[] ProcessImage(UploadImageModel model, string fileName) { using var fileStream = model.File.OpenReadStream(); byte[] bytes = new byte[model.File.Length]; fileStream.Read(bytes, 0, (int)model.File.Length); using (MemoryStream inStream = new MemoryStream(bytes)) { var img = Image.FromStream(inStream); var scaledImage = img.SetResizeResolution(model.Width, model.XDpi, model.YDpi); if (!string.IsNullOrEmpty(model.WatermarkText)) { scaledImage = scaledImage.SetWatermarkText(model.WatermarkText); } if (!string.IsNullOrEmpty(model.BackGroundColor)) { scaledImage = scaledImage.SetBackgroundColor(model.BackGroundColor); } var processedImage = Helper.ImageToByteArray(scaledImage, fileName); _cache.Set(model.ToString(), processedImage); WriteFile(processedImage, fileName); return(processedImage); } }
public async Task <IActionResult> Save(IFormFile file, UploadImageModel model, List <int> albums) { if (!ModelState.IsValid) { return(View(ImageForm, model)); } var image = new Image() { Id = model.Id, Title = model.Title, Tags = model.Tags, Url = model.Url }; if (!string.IsNullOrEmpty(image.Tags)) { tagRepository.Create(image.TagsList); } await SaveImage(file, image); await imageRepository.SaveChangesAsync(); SaveAlbums(image, albums); await imageRepository.SaveChangesAsync(); return(RedirectToAction(nameof(Index), nameof(Gallery))); }
public UploadImageResultModel UploadImage(UploadImageModel input) { List <string> imagesName = new List <string>(); UploadImageToLocalServer(input.ValidatedFile, input.FilePathOriginal); imagesName.Add(input.FilePathOriginal); var compressedImage = CompressImage(input.FilePathOriginal, input.QualityRate); SaveImage(compressedImage, input.FilePathCompressed); imagesName.Add(input.FilePathCompressed); var smallImage = ResizeImage(input.FilePathOriginal, Int32.Parse(_smallImage.Width), Int32.Parse(_smallImage.Height)); SaveImage(smallImage, input.FilePathSmall); imagesName.Add(input.FilePathSmall); return(new UploadImageResultModel { ResultModel = new ResultModel() { HasError = false, Message = "آپلود تصویر با موفقیت انجام شد." }, ImagesName = imagesName }); }
public async Task <IActionResult> UploadImage([FromForm] UploadImageModel model) { if (model == null) { return(this.InvalidRequest()); } string extension = Path.GetExtension(model.File.FileName); if (!AvailableImageExtensionList.Contains(extension, StringComparer.CurrentCultureIgnoreCase)) { return(this.Error(L["Please upload the correct format image file"].Value)); } string fileName = $"/upload/image/{Guid.NewGuid().ToString()}{extension.ToLower()}"; string physicalPath = this.Enviroment.ContentRootPath + "/App_Data" + fileName; string directoryName = Path.GetDirectoryName(physicalPath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } using (var stream = new FileStream(physicalPath, FileMode.Create)) { await model.File.CopyToAsync(stream); } return(this.Success(fileName)); }
public async Task <IActionResult> UploadNewImage(UploadImageModel uploadImage) { if (ModelState.IsValid) { // uploading path var path = Path.Combine(_environment.WebRootPath, @"images"); var fileName = uploadImage.ImageUpload.FileName; using (var fileStream = new FileStream(Path.Combine(path, fileName), FileMode.Create)) { await uploadImage.ImageUpload.CopyToAsync(fileStream); } var tags = uploadImage.Tags.Split(','); var model = new GalleryImage { Title = uploadImage.Title, Url = "/images/" + fileName, Created = new DateTime(), }; _context.GalleryImages.Add(model); _context.SaveChanges(); } ; return(RedirectToAction("Index", "Gallery")); }
public IActionResult Edit(int?id) { if (id == null) { return(NotFound()); } var image = imageRepository.GetWithAlbums(id.Value); if (image == null) { return(NotFound()); } var uploadModel = new UploadImageModel() { Id = image.Id, Title = image.Title, Tags = image.Tags, Url = image.Url, AllAlbums = albumsRepository.Get(), Albums = albumsImagesRepository.GetAlbumsTitlesWithImage(image.Id) }; return(View(ImageForm, uploadModel)); }
public async Task <IActionResult> UploadNewImage(UploadImageModel imageModel) { if (imageModel.ImageUpload == null || imageModel.ImageUpload.Length == 0) { return(Content("file not selected")); } var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot/images", imageModel.ImageUpload.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await imageModel.ImageUpload.CopyToAsync(stream); } var imageUrl = imageModel.ImageUpload.FileName; var tempImage = new GalleryImage { Created = DateTime.Now, Title = imageModel.Title, Url = "/images/" + imageUrl }; await _ctx.GalleryImages.AddAsync(tempImage); await _ctx.SaveChangesAsync(); return(RedirectToAction("Index", "Gallery")); }
public IActionResult Upload() { var model = new UploadImageModel(); // present a user with an empty form rather than pre-populated fields that get posted back to another action result return(View(model)); }
public IActionResult Upload() { var model = new UploadImageModel(); //await DownloadImageToDisplay("interiordesk.jpg"); return(View(model)); }
/// <summary> /// Create Event from specified dto. /// </summary> /// <param name="establishment"></param> /// <param name="uploadedImage"></param> /// <param name="dto"></param> /// <returns></returns> private Event CreateEvent(Establishment establishment, UploadImageModel uploadedImage, EventInsertDTO dto) { return(new Event( establishment.Id, dto.StartDate, dto.EndDate, dto.Name, dto.Description, uploadedImage.Image, uploadedImage.Thumbnail, dto.Location != null ? new Location( dto.Location.Street, dto.Location.Number, dto.Location.State, dto.Location.Country, dto.Location.City, new GeoJson2DGeographicCoordinates( dto.Location.Longitude, dto.Location.Latitude ) ) : establishment.Location, dto.Location == null, dto.Genres )); }
public async Task <Images[]> UploadImageInformation(UploadImageModel model) { using (var a = contextFactory.CreateDbContext()) { var user = await a.Users.Where(x => x.Id == httpContext.GetCurrentUserId()).FirstOrDefaultAsync(); if (user == null) { throw new ArgumentException("No person with that id"); } user.Images.Add(new Images() { Url = model.Url, DeleteUrl = model.DeleteURL, StoreId = model.Id, UserId = user.Id, UploadedAt = model.UploadedAt, Title = model.Title, Description = model.Description }); await a.SaveChangesAsync(); return(await GetOrganizationImages()); } }
public HttpResponseMessage UploadPhotoImageFile([FromBody] UploadImageModel model) { try { string targetFolder = HttpContext.Current.Server.MapPath("~/App_Data"); string fullPath = targetFolder + "/" + model.FilePath; byte[] imageBytes = Convert.FromBase64String(model.Base64Image); Image image; using (MemoryStream ms = new MemoryStream(imageBytes)) { image = Image.FromStream(ms); } Bitmap bitmap = new Bitmap(image); bitmap.Save(fullPath, System.Drawing.Imaging.ImageFormat.Jpeg); services.UserService.UpdateUserProfilePhotoPath(User.Identity.Name, model.FilePath); return(Request.CreateResponse(HttpStatusCode.OK)); } catch (Exception e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); } }
public static UploadImageModel PrepareModel(this UploadImageModel uploadImageModel, UploadImageDataContract input) { uploadImageModel.File = input.File; uploadImageModel.CompressionRate = input.CompressionRate; uploadImageModel.FilePath = input.FilePath; return(uploadImageModel); }
public IActionResult Upload() { // The user will be presented with a form which will later be posted var model = new UploadImageModel(); return(View(model)); }
public async Task <IActionResult> Upload(UploadImageModel uploadImageModel) { if (ModelState.IsValid) { var webRoot = _env.WebRootPath; var filePath = Path.Combine(webRoot.ToString() + "\\images\\" + uploadImageModel.ImageUpload.FileName); if (uploadImageModel.ImageUpload.FileName.Length > 0) { using (var stream = new FileStream(filePath, FileMode.Create)) { await uploadImageModel.ImageUpload.CopyToAsync(stream); } } var image = new GalleryImage { Title = uploadImageModel.Title, Tags = uploadImageModel.Tags.Split(",").Select(tag => new ImageTag { Description = tag }).ToList(), Created = DateTime.Today, Url = "/images/" + uploadImageModel.ImageUpload.FileName }; _image.AddImage(image); return(RedirectToAction("Index", "Gallery")); } return(View(uploadImageModel)); }
public ActionResult saveHead() { UploadImageModel model = new UploadImageModel(); model.headFileName = Request.Form["headFileName"].ToString(); model.x = Convert.ToInt32(Request.Form["x"]); model.y = Convert.ToInt32(Request.Form["y"]); model.width = Convert.ToInt32(Request.Form["width"]); model.height = Convert.ToInt32(Request.Form["height"]); if ((model == null)) { return(Json(new { msg = 0 })); } else { var filepath = Path.Combine(Server.MapPath("~/avatar/temp"), model.headFileName); string fileExt = Path.GetExtension(filepath); Random r = new Random(); var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + r.Next(10000) + fileExt; var path180 = Path.Combine(Server.MapPath("~/avatar/180"), filename); cutAvatar(filepath, model.x, model.y, model.width, model.height, 75L, path180, 180); //同时更新数据库》个人头像 string imgurl = "/avatar/180/" + filename; User user = _userService.getUserById(loginUser.userId); user.userImg = imgurl; _userService.updateUser(user); //更改用户登录的头像(cookies值) FormsAuthentication.SetAuthCookie(user.userImg, true); return(Json(new { msg = 1, newImg = imgurl })); } }
public ActionResult UploadImage(UploadImageModel model) { _ilog.Info(string.Format("方法名:{0};参数:{1}", "UploadImage", Serializer.ToJson(model))); var result = new StandardJsonResult(); result.Try(() => { if (!ModelState.IsValid) { throw new KnownException(ModelState.GetFirstError()); } Picture pic = new Picture(); pic.PictureGuid = model.Guid; pic.PictureName = model.FileName; HttpFileCollectionBase files = HttpContext.Request.Files; if (files.Count > 0) { pic.PictureStream = files[0].InputStream; bool f = service.SavePicture(pic); } }); _ilog.Info(string.Format("方法名:{0};执行结果:{1}", "UploadImage", Serializer.ToJson(result))); return(result); }
public IActionResult Upload() { // Present the user with an empty form, user fills it out & post to another actionResult (will handle all properties the user provide to the new object to be created) var model = new UploadImageModel(); return(View(model)); }
/// <summary> /// Create establishment from specified dto. /// </summary> /// <param name="imageUrl"></param> /// <param name="thumbnailUrl"></param> /// <param name="dto"></param> /// <returns></returns> private Establishment CreateEstablishment(UploadImageModel uploadedImage, RegisterEstablishmentDTO dto) { return(new Establishment( dto.Name, uploadedImage.Image, uploadedImage.Thumbnail, dto.Description, dto.Location != null ? new Location( dto.Location.Street, dto.Location.Number, dto.Location.State, dto.Location.Country, dto.Location.City, new GeoJson2DGeographicCoordinates( dto.Location.Longitude, dto.Location.Latitude ) ) : null, dto.EstablishmentTypes, dto.Availabilities != null ? dto.Availabilities.Select(availability => new Availability(availability.DayOfWeek, availability.OpenTime, availability.CloseTime)) : null )); }
public async Task <IActionResult> UploadFaceImageReturnCode([FromBody] UploadImageModel model) { try { var imageDataByteArray = Convert.FromBase64String(model.ImageData.Split(',').LastOrDefault()); var imageDataStream = new MemoryStream(imageDataByteArray); imageDataStream.Position = 0; if (imageDataStream == null || imageDataStream.Length == 0) { return(BadRequest("Dosya Tanımlanamadı.")); } var folderName = Path.Combine("Contents", "ProfilePics"); var filePath = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } var uniqueFileName = $"{Guid.NewGuid()}"; var dbPath = Path.Combine(folderName, uniqueFileName); using (var fileStream = new FileStream(Path.Combine(filePath, uniqueFileName), FileMode.Create)) { await imageDataStream.CopyToAsync(fileStream); } var hostingInformation = _hostingEnvironment.ContentRootPath; String fulldirectory = "./Contents/ProfilePics/" + uniqueFileName; String faceData = ""; FaceRecognitionDotNet.FaceRecognition abc = FaceRecognitionDotNet.FaceRecognition.Create(hostingInformation + "\\Contents\\ProfilePics\\"); var unknownImage = FaceRecognitionDotNet.FaceRecognition.LoadImageFile(fulldirectory); var returns = abc.FaceEncodings(unknownImage); if (returns.Count() > 0) { SerializationInfo info = new SerializationInfo(typeof(FaceRecognitionDotNet.FaceEncoding), new FormatterConverter()); StreamingContext context = new StreamingContext(); returns.First().GetObjectData(info, context); foreach (SerializationEntry entry in info) { var data = entry.Value; double[] array = (double[])data; faceData = String.Join(" ", array); break; } } var fileInfo = new System.IO.FileInfo(fulldirectory); fileInfo.Delete(); return(Ok(faceData)); } catch (Exception e) { return(BadRequest("Sistemde Hata Oluştu. " + e.Message)); } }
public ActionResult <ResponseModel <string> > UploadImage([FromHeader] string Authorization , UploadImageModel imageModel) { string token = Authorization.Split()[1]; string path = _userService.UploadImage(token, imageModel); return(ResponseModel <string> .FormResponse("path", path, "Unable to upload image")); }
public ImageController(IImageService imageService, RemoveImageRichModel removeImageRichModel, UploadImageModel uploadImageModel) { _imageService = imageService; _removeImageRichModel = removeImageRichModel; _uploadImageModel = uploadImageModel; }
public IActionResult Create() { var model = new UploadImageModel(); model.AllAlbums = albumsRepository.Get(); model.Albums = new List <string>(); return(View(ImageForm, model)); }
public ActionResult UploadImage(UploadImageModel model) { var x = 1; UploadImageModel md = model; try { const string prefix = "data:image/png;base64,"; string path = AppDomain.CurrentDomain.BaseDirectory + "UserImages"; var fileName = User.Identity.GetUserId() + "-" + DateTime.Now.ToString("yyyyMMddTHHmmss") + "-" + model.FileName; var photo = db.Photos.FirstOrDefault(p => p.Id == model.Id); var userId = User?.Identity?.GetUserId(); if (photo == null || photo.UserId != userId) { photo = new Photo { UserId = User.Identity.GetUserId(), ImagePath = fileName, CategoryId = model.CategoryId // category is not passed in update the model to add it }; db.Photos.Add(photo); } else { photo.ImagePath = fileName; } db.SaveChanges(); using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create)) { using (BinaryWriter bw = new BinaryWriter(fs)) { string base64; if (model.Image.StartsWith(prefix)) { base64 = model.Image.Substring(prefix.Length); } else { base64 = model.Image; } byte[] data = Convert.FromBase64String(base64); bw.Write(data); bw.Close(); } } return(new HttpStatusCodeResult(HttpStatusCode.OK)); } catch (Exception ex) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } }
public UploadImageResultModel UploadImage(UploadImageModel input) { Stopwatch sw = Stopwatch.StartNew(); var result = _imageService.UploadImage(input); sw.Stop(); _logger.LogWarning($"====> Uploading image - elapsed milli seconds : {sw.ElapsedMilliseconds}"); return(result); }
public ActionResult Upload(UploadImageModel model) { var imageKey = Ioc.Resolve <IImageService>().SaveImageAndReturnKey(BusinessType.Default, model.FileModel.ToImage()); var result = new JsonResult <object>(); result.Succeed(); result.Value = Tuple.Create(imageKey, ImageHelper.BuildSrc(imageKey, ImageSize.Full)); return(result); }
public ServiceResult <string> Upload(UploadImageModel model) { var account = new MerchantAccountComponent().GetById(this.GetMerchantAccountId()); return(new ServiceResult <string> { Data = new ImageComponent().UploadWithRegion(model.FileName, model.Base64Content, account.CountryId) }); }
public ActionResult UploadImage() { var folderList = _cloudinaryManager.GetFolderList(); var imageModel = new UploadImageModel() { Folders = new SelectList(folderList, dataTextField: "Name", dataValueField: "Path") }; return(View(imageModel)); }
public async Task <string> UploadImage(IFormFile formFile, string userId, string uploadedFileType) { string filePath = _appSettings.FolderPath.CompanyImagePath; var path = $"{Environment.CurrentDirectory}\\{_appSettings.FolderPath.RootFolder}\\{_appSettings.FolderPath.CompanyImagePath}"; string fileName = string.Empty; if (uploadedFileType == Constants.UploadProfileImage) { fileName = $"companyLogo.{formFile.FileName.Split('.')[1]}"; } else if (uploadedFileType == Constants.UploadHeaderLogoImage) { fileName = $"headerLogo.{formFile.FileName.Split('.')[1]}"; } else { fileName = $"loginBackgroundImage.{formFile.FileName.Split('.')[1]}"; } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string[] files = Directory.GetFiles(path, uploadedFileType == Constants.UploadProfileImage ? $"companyLogo*" : uploadedFileType == Constants.UploadBackgroundImageForLogin ? $"loginBackgroundImage*" : $"headerLogo*"); if (files.Length > 0) { if (File.Exists($"{files[0]}")) { File.Delete($"{files[0]}"); } } var fileData = Utility.Upload(formFile, path, fileName); UploadImageModel uploadImageModel = new UploadImageModel() { FileName = fileData.FilePath, UserId = userId }; if (fileData != null) { bool isSuccess = await _accountData.UploadPhoto(fileData.FilePath, uploadedFileType); if (isSuccess) { return($"{_appSettings.FolderPath.CompanyImagePath}/{fileData.FilePath}"); } } return(null); }
public ActionResult AllPictures() { var model = new List<UploadImageModel>(); var path = Server.MapPath("/content/images/products/"); var folder = new DirectoryInfo(path); var images = folder.GetFiles(); string[] sizes = { "B", "KB", "MB", "GB" }; for (int i = 0; i < images.Length; i++) { if (images[i].Extension != ".db") { double len = images[i].Length; int order = 0; while (len >= 1024 && order + 1 < sizes.Length) { order++; len = len/1024; } string result = String.Format("{0:0.##} {1}", len, sizes[order]); var item = new UploadImageModel { Name = images[i].Name, FileSize = result, ImageUrl = images[i].DirectoryName }; model.Add(item); } } return PartialView(model); }