protected bool LoadImageFromWeb(WebImage webImage, WebImageRequest imageRequest, HttpRequestParameters requestParameters = null, string subDirectory = null) { if (!imageRequest.LoadImageFromWeb || (webImage.File != null && !imageRequest.RefreshImage)) return false; HttpRequest httpRequest = new HttpRequest { Url = webImage.Url }; string file = _urlCache.GetUrlSubPath(httpRequest); if (subDirectory != null) file = zPath.Combine(subDirectory, file); string path = zPath.Combine(_urlCache.CacheDirectory, file); if (imageRequest.RefreshImage || !zFile.Exists(path)) HttpManager.CurrentHttpManager.LoadToFile(httpRequest, path, _urlCache.SaveRequest, requestParameters); webImage.File = file; if (zFile.Exists(path)) { Image image = LoadImageFromFile(path); if (image != null) { webImage.Width = image.Width; webImage.Height = image.Height; if (imageRequest.LoadImageToData) webImage.Image = image; } } return true; }
//Predicate<ImageMongoCache> filter = null public bool LoadImage(WebImage webImage, WebImageRequest imageRequest, HttpRequestParameters requestParameters = null) { //Trace.WriteLine($"WebImageMongo.LoadImage() : \"{webImage.Url}\" _imageCacheManager {_imageCacheManager}"); if (webImage.Url != null && webImage.Image == null) { try { Image image = null; if (_imageCacheManager != null) { ImageMongoCache imageCache = (ImageMongoCache)_imageCacheManager.GetImageCache(webImage.Url, requestParameters); //if (_imageFilter != null && !_imageFilter(imageCache)) // return false; image = imageCache.Image; } else if (imageRequest.LoadImageFromWeb) image = HttpManager.CurrentHttpManager.LoadImage(new HttpRequest { Url = webImage.Url }, requestParameters); if (imageRequest.LoadImageToData) webImage.Image = image; } catch (Exception ex) { Trace.WriteLine("error loading image \"{0}\"", webImage.Url); Trace.WriteLine(ex.Message); //return false; } } return true; }
public void SimpleGetBytesClonesArray() { WebImage image = new WebImage(_PngImageBytes); byte[] returnedContent = image.GetBytes(); Assert.False(ReferenceEquals(_PngImageBytes, returnedContent), "GetBytes should clone array."); Assert.Equal(_PngImageBytes, returnedContent); }
public void FilePathReturnsCorrectPath() { // Arrange string imageName = @"x:\My-test-image.png"; // Act WebImage image = new WebImage(GetContext(), s => _PngImageBytes, imageName); // Assert Assert.Equal(imageName, image.FileName); }
public void FilePathCanBeSet() { // Arrange string originalPath = @"x:\somePath.png"; string newPath = @"x:\someOtherPath.jpg"; // Act WebImage image = new WebImage(GetContext(), s => _PngImageBytes, originalPath); image.FileName = newPath; // Assert Assert.Equal(newPath, image.FileName); }
protected void LoadImageToData(WebImage webImage) { if (webImage.File == null || webImage.Image != null) return; // _urlCache.CacheDirectory string path = zPath.Combine(GetCacheDirectory(), webImage.File); if (path != null && zFile.Exists(path)) { webImage.Image = LoadImageFromFile(path); } else { Trace.WriteLine("error unable to load image url \"{0}\" from file \"{1}\"", webImage.Url, path); } }
public static bool LoadImage(WebImage image, HttpRequestParameters_v1 requestParameters = null, Predicate<ImageMongoCache_v1> filter = null) { if (image.Url != null && image.Image == null) { if (__imageCacheManager != null) { ImageMongoCache_v1 imageCache = (ImageMongoCache_v1)__imageCacheManager.GetImageCache(image.Url, requestParameters); if (filter != null && !filter(imageCache)) return false; image.Image = imageCache.Image; } else image.Image = pb.old.Http_v2.LoadImageFromWeb(image.Url, requestParameters); } return true; }
/// <summary> /// コンストラクタ /// </summary> /// <param name="source">関連付けるWebImageオブジェクト</param> /// <param name="visionApiSubscriptionKey">Microsoft Vision API のSubscription Key</param> /// <param name="logger">ログメッセージ通知オブジェクト</param> public WebImageViewModel(WebImage source, string visionApiSubscriptionKey, ILogger logger) { this.source = source; this.logger = logger; this.visionApiSubscriptionKey = visionApiSubscriptionKey; //Model(WebImage)のプロパティをReactivePropertyに変換 Thumbnail = source.ObserveProperty(x => x.Thumbnail).ToReadOnlyReactiveProperty(); DisplayImage = source.ObserveProperty(x => x.DisplayImage).ToReadOnlyReactiveProperty(); Overlay = source.ObserveProperty(x => x.Overlay).ToReadOnlyReactiveProperty(); SourceUrl = source.ObserveProperty(x => x.SourceUrl).ToReadOnlyReactiveProperty(); SourceTitle = source.ObserveProperty(x => x.SourceTitle).ToReadOnlyReactiveProperty(); ImageProperty = source.ObserveProperty(x => x.ImageProperty).ToReadOnlyReactiveProperty(); //実行中フラグ IsProcessing = progress.IsProcessingObservable.StartWith(false) .ToReadOnlyReactiveProperty(); //プログレスバーの表示切替 - 実行中のみ表示する ProgressVisibility = IsProcessing .Select(x => x ? Visibility.Visible : Visibility.Collapsed) .ToReadOnlyReactiveProperty(); //画像のサイズ変更時に実行するコマンド SizeChangedCommand = new ReactiveCommand<Size>(); SizeChangedCommand .DistinctUntilChanged() .Throttle(TimeSpan.FromMilliseconds(200)) .Subscribe(size => { //現在のサイズで 顔領域の矩形を再描画 source.DrawFaceRect(size); //最新のサイズを保存しておく ⇒画像再選択時に使う imageSize = size; }) .AddTo(disposables); //リンク元ページURLのハイパーリンククリック時 NavigateCommand = new ReactiveCommand(); NavigateCommand.Subscribe(_ => { Process.Start(source.SourceUrl); }).AddTo(disposables); }
// HttpRequestParameters requestParameters = null protected bool LoadImageFromWeb(WebImage webImage, WebImageRequest imageRequest, string subDirectory = null) { if (!imageRequest.LoadImageFromWeb || (webImage.File != null && !imageRequest.RefreshImage)) return false; HttpRequest httpRequest = new HttpRequest { Url = webImage.Url, ReloadFromWeb = imageRequest.RefreshImage }; //string file = _urlCache.GetUrlSubPath(httpRequest); //if (subDirectory != null) // file = zPath.Combine(subDirectory, file); //string path = zPath.Combine(_urlCache.CacheDirectory, file); //if (imageRequest.RefreshImage || !zFile.Exists(path)) // HttpManager.CurrentHttpManager.LoadToFile(httpRequest, path, _urlCache.SaveRequest, requestParameters); //webImage.File = file; //UrlCachePathResult urlCachePath = LoadHttpToCache(httpRequest, subDirectory); //webImage.File = urlCachePath.SubPath; //string path = urlCachePath.Path; //if (zFile.Exists(path)) //{ // Image image = LoadImageFromFile(path); // if (image != null) // { // webImage.Width = image.Width; // webImage.Height = image.Height; // if (imageRequest.LoadImageToData) // webImage.Image = image; // } //} HttpResult<Image> httpResult = LoadImage(httpRequest, subDirectory); if (httpResult.Success) { Image image = httpResult.Data; webImage.File = httpResult.Http.HttpRequest.UrlCachePath?.SubPath; webImage.Width = image.Width; webImage.Height = image.Height; if (imageRequest.LoadImageToData) webImage.Image = image; return true; } else return false; }
protected void LoadImageToData(WebImage webImage) { if (webImage.File == null || webImage.Image != null) return; string path = zPath.Combine(_urlCache.CacheDirectory, webImage.File); if (path != null && zFile.Exists(path)) { //try //{ // webImage.Image = zimg.LoadFromFile(path); //} //catch (Exception exception) //{ // Trace.WriteLine("error unable to load image url \"{0}\" from file \"{1}\"", webImage.Url, path); // Trace.Write("error : "); // Trace.WriteLine(exception.Message); //} webImage.Image = LoadImageFromFile(path); } else { Trace.WriteLine("error unable to load image url \"{0}\" from file \"{1}\"", webImage.Url, path); } }
public void AddImageWatermarkThrowsOnNegativePadding() { WebImage watermark = new WebImage(_BmpImageBytes); WebImage image = new WebImage(_JpgImageBytes); Assert.ThrowsArgumentGreaterThanOrEqualTo( () => image.AddImageWatermark(watermark, padding: -10), "padding", "0"); }
public void AddImageWatermarkThrowsOnIncorrectHorizontalAlignment() { WebImage watermark = new WebImage(_BmpImageBytes); WebImage image = new WebImage(_JpgImageBytes); Assert.Throws<ArgumentException>( () => image.AddImageWatermark(watermark, horizontalAlign: "horizontal"), "The \"horizontalAlign\" value is invalid. Valid values are: \"Right\", \"Left\", and \"Center\"."); }
public ActionResult PostTheEditedProfile(Item2 form, HttpPostedFileBase file) { string imagePath2 = ""; WebImage photo = null; var newFileName = ""; var imagePath = ""; Item2 Data = form; var dataFormat = new dataFormatHandler(); if (ModelState.IsValid) { //try //{ if (file != null) { photo = WebImage.GetImageFromRequest(); if (photo != null) { newFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(photo.FileName); imagePath = @"~/uploads/" + newFileName; //string imagePath = @"images\" + photo.FileName; //photo.Save(@"~\" + imagePath); imagePath2 = Server.MapPath(imagePath); } //Extract Image File Name. //string fileName = System.IO.Path.GetFileName(file.FileName); ////Set the Image File Path. //string filePath = Path.Combine("~/UploadedFiles/", fileName); /*"~/UploadedFiles/" + fileName;*/ ////Save the Image File in Folder. //file.SaveAs(Server.MapPath(imagePath2)); file.SaveAs(Server.MapPath(imagePath)); //Insert the Image File details in Table. //FilesEntities entities = new FilesEntities(); //entities.Files.Add(new File //{ // Name = fileName, // Path = filePath //}); //entities.SaveChanges(); List <string> tempImages = Data.images.ToList(); tempImages.Add(imagePath); tempImages.Add(imagePath2); Data.images = tempImages.ToArray(); } else { Data.file = dataFormat.stringIsNull(Data.file); Data.images[0] = dataFormat.stringIsNull(Data.images[0]); } ViewBag.FileStatus = "File uploaded successfully."; //} //catch (Exception) //{ // ViewBag.FileStatus = "Error while file uploading."; //} } Data.caution = dataFormat.stringIsNull(Data.caution); Data.description = dataFormat.stringIsNull(Data.description); Data.uid = dataFormat.stringIsNull(Data.uid); Data.title = dataFormat.stringIsNull(Data.title); //if (Data.reward_max = null) //{ // Data.reward_max = 0; //} if (Data.locations == null) { Data.locations = new string[] { "null" }; } Data.status = dataFormat.stringIsNull(Data.status); Data.nationality = dataFormat.stringIsNull(Data.nationality); Data.locations[0] = dataFormat.stringIsNull(Data.locations[0]); dataHandler.UpdateAProfile(Data); return(View(Data)); }
public async Task <ActionResult> CreateAdminUser(UserVM userVM, HttpPostedFileBase file) { if (!ModelState.IsValid) { return(View(userVM)); } int idForAvatar = 0; using (ChekitDB chekitDB = new ChekitDB()) { if (await chekitDB.Users.AnyAsync(x => x.Login == userVM.Login)) { ModelState.AddModelError("loginmatch", $"Логин {userVM.Login} занят"); return(View(userVM)); } else if (await chekitDB.Users.AnyAsync(x => x.Email == userVM.Email)) { ModelState.AddModelError("emailmatch", $"Email {userVM.Email} занят"); return(View(userVM)); } UsersDTO usersDTO = new UsersDTO(); usersDTO.Login = userVM.Login; usersDTO.Email = userVM.Email; usersDTO.Password = userVM.Password; usersDTO.BanStatus = false; usersDTO.LinksCount = 0; usersDTO.Role = "Админ"; chekitDB.Users.Add(usersDTO); await chekitDB.SaveChangesAsync(); int id = usersDTO.UserId; int roleId = 1; UserRoleDTO userRole = new UserRoleDTO() { UserId = id, RoleId = roleId }; chekitDB.UserRoles.Add(userRole); await chekitDB.SaveChangesAsync(); idForAvatar = usersDTO.UserId; } TempData["OK"] = "Админ создан"; #region UploadAvatar var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Avatars\\Uploads")); var pathString1 = Path.Combine(originalDirectory.ToString(), "UserAvatars"); var pathString2 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + idForAvatar.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + idForAvatar.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + idForAvatar.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + idForAvatar.ToString() + "\\Gallery\\Thumbs"); if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } string[] extensions = { "image/jpg", "image/jpeg", "image/gif", "image/png" }; if (file != null && file.ContentLength > 0) { string extension = file.ContentType.ToLower(); int counter = 0; foreach (var item in extensions) { if (extension != item) { counter++; if (counter == extensions.Length) { ModelState.AddModelError("errorFormat", "Неправильный формат файла"); return(View(userVM)); } } } string avatarName = file.FileName; using (ChekitDB chekitDB = new ChekitDB()) { UsersDTO usersDTO = await chekitDB.Users.FindAsync(idForAvatar); usersDTO.AvatarName = avatarName; await chekitDB.SaveChangesAsync(); } var pathOriginalAvatar = string.Format($"{pathString2}\\{avatarName}"); var pathLittleAvatar = string.Format($"{pathString3}\\{avatarName}"); file.SaveAs(pathOriginalAvatar); WebImage littleAvatar = new WebImage(file.InputStream); littleAvatar.Resize(150, 150); littleAvatar.Save(pathLittleAvatar); } #endregion return(RedirectToAction("Index")); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { if (!ModelState.IsValid) { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } return(View(model)); } //Make sure productname is unique using (Db db = new Db()) { if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That product name id taken!"); return(View(model)); } } int id; using (Db db = new Db()) { ProductDTO productdto = new ProductDTO(); productdto.Name = model.Name; productdto.Slug = model.Name.Replace(" ", "-").ToLower(); productdto.Description = model.Description; productdto.Price = model.Price; productdto.CategoryId = model.CategoryId; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); productdto.CategoryName = catDTO.Name; db.Products.Add(productdto); db.SaveChanges(); id = productdto.Id; } //set tempdata message TempData["SM"] = "You have added a product!"; #region Upload image var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } if (file != null && file.ContentLength > 0) { string ext = file.ContentType.ToLower(); if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded or wrong image extension"); } } string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } var path = string.Format("{0}\\{1}", pathString2, imageName); var path2 = string.Format("{0}\\{1}", pathString3, imageName); file.SaveAs(path); WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion return(RedirectToAction("AddProduct")); }
public void SaveUsesOriginalFormatForStreamsWhenNoFormatIsSpecified() { // Arrange // Use rooted path so we by pass using HttpContext var specifiedOutputFile = @"x:\some-dir\foo.jpg"; string actualOutputFile = null; Action<string, byte[]> saveAction = (fileName, content) => { actualOutputFile = fileName; }; // Act WebImage image = new WebImage(_PngImageBytes); image.Save(GetContext(), saveAction, filePath: specifiedOutputFile, imageFormat: null, forceWellKnownExtension: true); // Assert Assert.Equal(Path.GetExtension(actualOutputFile), ".png"); }
public void CanAddImageWatermarkWithFileName() { // Arrange var context = GetContext(); WebImage image = new WebImage(_BmpImageBytes); WebImage watermark = new WebImage(_JpgImageBytes); // Act var watermarkedWithImageArgument = image.AddImageWatermark(watermark).GetBytes(); var watermarkedWithFilePathArgument = image.AddImageWatermark(context, (name) => _JpgImageBytes, @"x:\jpegimage.jpg", width: 0, height: 0, horizontalAlign: "Right", verticalAlign: "Bottom", opacity: 100, padding: 5).GetBytes(); Assert.Equal(watermarkedWithImageArgument, watermarkedWithFilePathArgument); }
public static void UploadImage(this CloudBlobContainer StorageContainer, string blobName, WebImage image) { CloudBlockBlob blob = StorageContainer.GetBlockBlobReference(blobName); blob.Properties.ContentType = "image/" + image.ImageFormat; using (var stream = new MemoryStream(image.GetBytes(), writable: false)) { blob.UploadFromStream(stream); } }
public ActionResult Register(RegisterModel model) { int genNumber = randomInteger.Next(1234567890); model.RegistrationType = "Student"; if (ModelState.IsValid) { // Attempt to register the user try { if (model.RegistrationType == "Student") { try { if (Request.Files.Count > 0) { HttpPostedFileBase file = Request.Files[0]; if (file.ContentLength > 0 && file.ContentType.ToUpper().Contains("JPEG") || file.ContentType.ToUpper().Contains("PNG")) { WebImage img = new WebImage(file.InputStream); if (img.Width > 200) { img.Resize(200, 200, true, true); } string fileName = Path.Combine(Server.MapPath("~/Uploads/Items/"), Path.GetFileName(genNumber + file.FileName)); img.Save(fileName); model.ImageUrl = fileName; } else { ViewBag.SchoolId = new SelectList(db.Schools, "SchoolId", "SchoolName", model.SchoolId); return(View(model)); } } WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { EmailAddress = model.EmailAddress, PhoneNumber = model.PhoneNumber, RegistrationType = model.RegistrationType, ImageUrl = model.ImageUrl, Departmentid = model.DepartmentId, LevelId = model.Levelid, SurName = model.SurName, FirstName = model.FirstName, OtherNames = model.OtherNames, RegistrationNumber = model.RegistrationNumber, IsComplated = true }); WebSecurity.Login(model.UserName, model.Password); if (!Roles.RoleExists("Student")) { Roles.CreateRole("Student"); } Roles.AddUsersToRoles(new[] { model.UserName }, new[] { "Student" }); return(RedirectToAction("Index", "Profile")); } catch { ViewBag.SchoolId = new SelectList(db.Schools, "SchoolId", "SchoolName", model.SchoolId); return(View(model)); } } } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } } // If we got this far, something failed, redisplay form ViewBag.SchoolId = new SelectList(db.Schools, "SchoolId", "SchoolName", model.SchoolId); return(View(model)); }
public ActionResult Edit(PromoViewModel viewModel) { CommonDataService cds = new CommonDataService(); CommonModel cm = new CommonModel(); cm = cds.GenerateCommonModel(); Session["FaceBook"] = cm.FaceBook; Session["Twitter"] = cm.Twitter; Session["Youtube"] = cm.Youtube; Session["Instagram"] = cm.Instagram; Session["PhoneNumber"] = cm.PhoneNumber; Session["Email"] = cm.Email; Session["ShoppingHours"] = cm.ShoppingHours; PromoDataService dataService = new PromoDataService(); string promoId = (string)Request.Form["edit_PromoId"]; string imageString = (string)Request.Form["edit_ImageString"]; try { if (ModelState.IsValid) { WebImage photo = null; var newFileName = ""; var imagePath = ""; photo = WebImage.GetImageFromRequest(); if (photo != null) { newFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(photo.FileName); imagePath = @"Contents\Images\Promo\" + newFileName; photo.Save(@"~\" + imagePath); viewModel.PromoModel.PromoId = int.Parse(promoId); viewModel.PromoModel.ImageString = imagePath; } else { viewModel.PromoModel.PromoId = int.Parse(promoId); viewModel.PromoModel.ImageString = imageString; } dataService.UpdatePromo(viewModel.PromoModel); return(RedirectToAction("Edit", "Promo")); } else { viewModel.PromoModel.PromoId = int.Parse(promoId); viewModel.PromoModel.ImageString = imageString; return(View(viewModel)); } } catch (Exception ex) { throw ex; } finally { dataService = null; } }
public virtual async Task <ActionResult> Add(RegisterViewModel userViewModel, HttpPostedFileBase userImage) { if (userViewModel.Id.HasValue) { ModelState.Remove("Password"); ModelState.Remove("ConfirmPassword"); } if (!ModelState.IsValid) { return(View(userViewModel)); } if (!userViewModel.Id.HasValue) { var user = new ApplicationUser { UserName = userViewModel.UserName, Email = userViewModel.Email, EmailConfirmed = true }; var adminresult = await _userManager.CreateAsync(user, userViewModel.Password); if (adminresult.Succeeded) { var result = await _userManager.AddToRolesAsync(user.Id, "Admin"); if (!result.Succeeded) { ModelState.AddModelError("", result.Errors.First()); return(View()); } } else { ModelState.AddModelError("", adminresult.Errors.First()); return(View()); } TempData["message"] = "کاربر جدید با موفقیت در سیستم ثبت شد"; } else { var user = await _userManager.FindByIdAsync(userViewModel.Id.Value); if (user == null) { return(HttpNotFound()); } user.UserName = userViewModel.UserName; user.Email = userViewModel.Email; await _unitOfWork.SaveAllChangesAsync(); TempData["message"] = "کاربر مورد نظر با موفقیت ویرایش شد"; } if (userImage != null) { var img = new WebImage(userImage.InputStream); img.Resize(161, 161, true, false).Crop(1, 1); img.Save(Server.MapPath("~/UploadedFiles/Avatars/" + userViewModel.UserName + ".png")); } return(RedirectToAction(MVC.User.Admin.ActionNames.Index)); }
public ActionResult AddProduct(ProductVM obj, HttpPostedFileBase file) { //Check ModelState is Valid if (!ModelState.IsValid) { using (Db _context = new Db()) { obj.Catagories = new SelectList(_context.Catagories.ToList(), "Id", "Name"); return(View(obj)); } } //MakeSure the Product Name is unique using (Db _context = new Db()) { if (_context.Products.Any(a => a.Name == obj.Name)) { obj.Catagories = new SelectList(_context.Catagories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The Product Name is Taken..!"); return(View(obj)); } } //Declare Product ID int Id; //Init And save ProductDTO using (Db _context = new Db()) { ProductDTO objPro = new ProductDTO(); objPro.Name = obj.Name; objPro.Description = obj.Description; objPro.Slug = obj.Name.Replace(" ", "-").ToLower(); objPro.Price = obj.Price; objPro.CatagoryId = obj.CatagoryId; CatagoryDTO objCat = _context.Catagories.FirstOrDefault(x => x.Id == obj.CatagoryId); objPro.catagoryName = objCat.Name; _context.Products.Add(objPro); _context.SaveChanges(); //Get the ID Id = objPro.Id; } //Set tempData Message TempData["SM"] = "You Have Added the product Succesfuly"; #region Upload_Image //Create The Necessary Directories var OriginalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); string PathString1 = Path.Combine(OriginalDirectory.ToString(), "Products"); string PathString2 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + Id.ToString()); string PathString3 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + Id.ToString() + "\\Thumbs"); string PathString4 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + Id.ToString() + "\\Gallary"); string PathString5 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + Id.ToString() + "\\Gallary\\Thumbs"); if (!Directory.Exists(PathString1)) { Directory.CreateDirectory(PathString1); } if (!Directory.Exists(PathString2)) { Directory.CreateDirectory(PathString2); } if (!Directory.Exists(PathString3)) { Directory.CreateDirectory(PathString3); } if (!Directory.Exists(PathString4)) { Directory.CreateDirectory(PathString4); } if (!Directory.Exists(PathString5)) { Directory.CreateDirectory(PathString5); } //Check If the File was Upload if (file != null && file.ContentLength > 0) { //Get the File Extension string ex = file.ContentType.ToLower(); //Verify the file Extension if (ex != "image/jpg" && ex != "image/jpeg" && ex != "image/pjepg" && ex != "image/gif" && ex != "image/x-png" && ex != "image/png") { using (Db _context = new Db()) { obj.Catagories = new SelectList(_context.Catagories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The Image was not Uploaded- Wrong Image Extension..!"); return(View(obj)); } } //Init the Image Name string ImagName = file.FileName; //Save ImageName to DTO using (Db _context = new Db()) { ProductDTO objP = _context.Products.Find(Id); objP.ImgName = ImagName; _context.SaveChanges(); } //Set Original And Thumb Images Paths var path1 = string.Format("{0}\\{1}", PathString2, ImagName); var path2 = string.Format("{0}\\{1}", PathString3, ImagName); //Save Original file.SaveAs(path1); //Create and Save Thumb WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion return(RedirectToAction("AddProduct")); }
public static WebImage ImageResize(this WebImage webImage, ImageSavingInfo imageSavingInfo) { return(webImage.ImageResize(new Size(imageSavingInfo.MaxWidth, imageSavingInfo.MaxHeight), imageSavingInfo.Crop)); }
public void AddImageWatermarkWithFileNameThrowsExceptionWhenWatermarkDirectoryDoesNotExist() { var context = GetContext(); WebImage image = new WebImage(_BmpImageBytes); Assert.Throws<DirectoryNotFoundException>( () => image.AddImageWatermark(context, s => { throw new DirectoryNotFoundException(); }, @"x:\path\does\not\exist", width: 0, height: 0, horizontalAlign: "Right", verticalAlign: "Bottom", opacity: 100, padding: 5)); }
public void AddImageWatermarkWithFileNameThrowsExceptionWhenWatermarkFileDoesNotExist() { var context = GetContext(); WebImage image = new WebImage(_BmpImageBytes); Assert.Throws<FileNotFoundException>( () => image.AddImageWatermark(context, s => { throw new FileNotFoundException(); }, @"x:\there-is-no-file.jpg", width: 0, height: 0, horizontalAlign: "Right", verticalAlign: "Bottom", opacity: 100, padding: 5)); }
public ActionResult ArizaBildirimi(ArizaViewModel model) { if (!ModelState.IsValid) { return(View(model)); } try { var arizaRepo = new ArizaRepository(); var ariza = new Ariza() { MusteriId = HttpContext.User.Identity.GetUserId(), Aciklama = model.Aciklama, MarkaAdi = model.MarkaAdi, ModelAdi = model.ModelAdi, Adres = model.Adres, ArizaOlusturmaTarihi = DateTime.Now, }; arizaRepo.Insert(ariza); if (model.PostedFile.Count > 0) { model.PostedFile.ForEach(file => { if (file != null && file.ContentLength > 0) { string fileName = Path.GetFileNameWithoutExtension(file.FileName); string extName = Path.GetExtension(file.FileName); fileName = StringHelpers.UrlFormatConverter(fileName); fileName += StringHelpers.GetCode(); var klasoryolu = Server.MapPath("~/Upload/"); var dosyayolu = Server.MapPath("~/Upload/") + fileName + extName; if (!Directory.Exists(klasoryolu)) { Directory.CreateDirectory(klasoryolu); } file.SaveAs(dosyayolu); WebImage img = new WebImage(dosyayolu); img.Resize(250, 250, false); img.Save(dosyayolu); new FotografRepository().Insert(new Fotograf() { ArizaId = ariza.Id, Yol = "/Upload/" + fileName + extName }); } }); } var fotograflar = new FotografRepository().GetAll(x => x.ArizaId == ariza.Id).ToList(); ariza.ArizaFoto = fotograflar.Select(x => x.Yol).ToList(); arizaRepo.Update(ariza); TempData["Message"] = "Kaydınız alınlıştır"; return(RedirectToAction("ArizaBildirimi", "Musteri")); } catch (Exception ex) { TempData["Model"] = new ErrorViewModel() { Text = $"Bir hata oluştu {ex.Message}", ActionName = "ArizaBildirimi", ControllerName = "Musteri", ErrorCode = 500 }; return(RedirectToAction("Error", "Home")); } }
public void SaveThrowsWhenPathIsNull() { Action<string, byte[]> saveAction = (path, content) => { }; // this constructor will not set path byte[] originalContent = _BmpImageBytes; WebImage image = new WebImage(originalContent); Assert.ThrowsArgumentNullOrEmptyString( () => image.Save(GetContext(), saveAction, filePath: null, imageFormat: null, forceWellKnownExtension: true), "filePath"); }
/// <summary> /// Web上からテクスチャを取得する。 /// キャッシュにあれば、キャッシュから返す /// </summary> /// <param name="url"></param> /// <returns></returns> public IEnumerator DownloadWebTexutre(string url) { //ディクショナリ存在チェック if (DicImage.ContainsKey(url)) { yield break; } //ファイル名、ファイルパス生成 string path = CreateFilePath(url); //ファイル名取得失敗時 if (path != "") { //最新ニュースデータ取得 var Async = WebImage.GetImage(url); //非同期実行 yield return(Async); //データ取得 Texture2D texture = (Texture2D)Async.Current; if (texture != null) { try { if (!texture.isBogus()) { //PNGで保存 TextureUtil.SavePng(texture, path); //辞書に登録 this.Add(new DatImageFileInfo(url, path, DateTime.Now)); } else { //ノーイメージをセット texture = GetNoImageTex(); //辞書に登録 this.Add(new DatImageFileInfo(url, "", DateTime.Now)); } } catch { Debug.Log("ファイル保存失敗:" + url); } } else { //ノーイメージをセット texture = GetNoImageTex(); //辞書に登録 this.Add(new DatImageFileInfo(url, "", DateTime.Now)); } //セーブ Save(); } else { //辞書に登録 this.Add(new DatImageFileInfo(url, "", DateTime.Now)); } }
public async Task <ActionResult> ChangeProfilePicture(HttpPostedFileBase file) { UserProfilePhoto userP = null; string userId = User.Identity.GetUserId(); var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", ".jpeg", ".JPG", ".GIF", ".Gif", ".gif" }; var ext = Path.GetExtension(file.FileName); var retrievedUserPhoto = _applicationDbContext.UserProfilePhotos.SingleOrDefault(u => u.UserId == userId); if (retrievedUserPhoto == null) { } else { string userImageToDelete = retrievedUserPhoto.ImageName; string path = Request.MapPath("~/ProfilePhoto/" + userImageToDelete); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } if (file != null && allowedExtensions.Contains(ext)) { userP = new UserProfilePhoto(); string filename = null; //string filename = Guid.NewGuid() + Path.GetExtension(file.FileName); //string filename = Guid.NewGuid() + file.FileName; WebImage img = new WebImage(file.InputStream); if (img.Width > 120) { img.Resize(120, 44); } int length = file.FileName.IndexOf("."); if (length > 0) { filename = file.FileName.Substring(0, length); } string randFileName = Guid.NewGuid() + Path.GetExtension(filename); //string filename = file.FileName.Substring(file.FileName.IndexOf(".") + 1).Trim(); img.Save(Path.Combine(Server.MapPath("~/ProfilePhoto"), filename)); if (retrievedUserPhoto == null) { userP.UserId = User.Identity.GetUserId(); userP.ImageName = filename + Path.GetExtension(img.FileName); userP.DateCreated = DateTime.UtcNow; _applicationDbContext.UserProfilePhotos.Add(userP); await _applicationDbContext.SaveChangesAsync(); return(RedirectToAction("Index", new { Message = ManageMessageId.AddProfileImage })); } else { var userPictureToUpdate = _applicationDbContext.UserProfilePhotos .Where(i => i.UserId == userId) .Single(); if (TryUpdateModel(userPictureToUpdate, "", new string[] { "UserProfilePhotoId", "UserId", "ImageName", "DateCreated" })) { try { userPictureToUpdate.ImageName = filename + Path.GetExtension(img.FileName); _applicationDbContext.Entry(userPictureToUpdate).State = EntityState.Modified; await _applicationDbContext.SaveChangesAsync(); return(RedirectToAction("Index", new { Message = ManageMessageId.AddProfileImage })); } catch (Exception /* dex */) { //Log the error (uncomment dex variable name after DataException and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, do contact us."); } } } } ModelState.AddModelError("", "Failed upload valid photo"); return(View()); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { //get product Id int id = model.Id; //populate the catagory select list amd Image Gallery using (Db _context = new Db()) { model.Catagories = new SelectList(_context.Catagories.ToList(), "Id", "Name"); } model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallary/Thumbs")) .Select(fn => Path.GetFileName(fn)); //Check the Model State if (!ModelState.IsValid) { return(View(model)); } //Make sure the product name is unique.. using (Db _context = new Db()) { if (_context.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "The name of the Products is exist...!"); return(View(model)); } } //Update the Product... using (Db _context = new Db()) { ProductDTO obj = _context.Products.Find(id); obj.Name = model.Name; obj.Slug = model.Name.Replace(" ", "-").ToLower(); obj.Price = model.Price; obj.Description = model.Description; obj.CatagoryId = model.CatagoryId; if (model.ImgName != null) { obj.ImgName = model.ImgName; } CatagoryDTO objcat = _context.Catagories.FirstOrDefault(x => x.Id == model.CatagoryId); obj.catagoryName = objcat.Name; _context.SaveChanges(); } //Set tempdate message TempData["SM"] = "You have Edit the product successfuly.."; #region Image Upload //Check the File Upload if (file != null && file.ContentLength > 0) { //Get the Extension string exe = file.ContentType.ToLower(); //verify the extension if (exe != "image/jpg" && exe != "image/jpeg" && exe != "image/pjepg" && exe != "image/gif" && exe != "image/x-png" && exe != "image/png") { using (Db _context = new Db()) { ModelState.AddModelError("", "The Image was not Uploaded- Wrong Image Extension..!"); return(View(model)); } } //Set Upload Directory Path var OriginalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); string PathString1 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + id.ToString()); string PathString2 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); //Delete Files From Directorr DirectoryInfo dI1 = new DirectoryInfo(PathString1); DirectoryInfo dI2 = new DirectoryInfo(PathString2); foreach (FileInfo item in dI1.GetFiles()) { item.Delete(); } foreach (FileInfo item1 in dI2.GetFiles()) { item1.Delete(); } //Save Image Name string ImName = file.FileName; using (Db _context = new Db()) { ProductDTO objP = _context.Products.Find(id); objP.ImgName = ImName; _context.SaveChanges(); } //Set the Original and Thumbs Imagess var path1 = string.Format("{0}\\{1}", PathString1, ImName); var path2 = string.Format("{0}\\{1}", PathString2, ImName); //Save Original file.SaveAs(path1); //Create and Save Thumb WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion return(RedirectToAction("EditProduct")); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { // Get product id int id = model.Id; // Populate categories select list and gallery images using (ApplicationDbContext db = new ApplicationDbContext()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")) .Select(fn => Path.GetFileName(fn)); // Check model state if (!ModelState.IsValid) { return(View(model)); } // Make sure product name is unique using (ApplicationDbContext db = new ApplicationDbContext()) { if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } // Update product using (ApplicationDbContext db = new ApplicationDbContext()) { ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.ImageName = model.ImageName; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = catDTO.Name; db.SaveChanges(); } // Set TempData message TempData["SM"] = "You have edited the product!"; #region Image Upload // Check for file upload if (file != null && file.ContentLength > 0) { // Get extension string ext = file.ContentType.ToLower(); // Verify extension if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (ApplicationDbContext db = new ApplicationDbContext()) { ModelState.AddModelError("", "The image was not uploaded - wrong image extension."); return(View(model)); } } // Set uplpad directory paths var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); // Delete files from directories DirectoryInfo di1 = new DirectoryInfo(pathString1); DirectoryInfo di2 = new DirectoryInfo(pathString2); foreach (FileInfo file2 in di1.GetFiles()) { file2.Delete(); } foreach (FileInfo file3 in di2.GetFiles()) { file3.Delete(); } // Save image name string imageName = file.FileName; using (ApplicationDbContext db = new ApplicationDbContext()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } // Save original and thumb images var path = string.Format("{0}\\{1}", pathString1, imageName); var path2 = string.Format("{0}\\{1}", pathString2, imageName); file.SaveAs(path); WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion // Redirect return(RedirectToAction("EditProduct")); }
public static bool SaveImage(int id, HttpPostedFileBase file, string folderName) { var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", HttpContext.Current.Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), folderName); var pathString2 = Path.Combine(originalDirectory.ToString(), folderName + "\\" + id.ToString()); if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (file != null && file.ContentLength > 0) { // Get file extension string ext = file.ContentType.ToLower(); // Verify extension if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { return(false); } // Set original and thumb image paths var path = string.Format("{0}\\{1}", pathString2, file.FileName); // Save original file.SaveAs(path); #region AdditionalFolders //Only for Products var pathString3 = Path.Combine(originalDirectory.ToString(), folderName + "\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), folderName + "\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), folderName + "\\" + id.ToString() + "\\Gallery\\Thumbs"); if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } var path2 = string.Format("{0}\\{1}", pathString3, file.FileName); // Create and save thumb WebImage img = new WebImage(file.InputStream); img.Resize(150, 150); img.Save(path2); #endregion } return(true); }
public async Task <ActionResult> EditUser(UserProfileVM userVM, HttpPostedFileBase file) { int userId = userVM.UserId; if (!ModelState.IsValid) { return(View("Error")); } using (ChekitDB chekitDB = new ChekitDB()) { if (await chekitDB.Users.Where(x => x.UserId != userVM.UserId).AnyAsync(x => x.Login == userVM.Login)) { ModelState.AddModelError("loginmatch", $"Логин {userVM.Login} занят"); return(View(userVM)); } else if (await chekitDB.Users.Where(x => x.UserId != userVM.UserId).AnyAsync(x => x.Email == userVM.Email)) { ModelState.AddModelError("emailmatch", $"Email {userVM.Email} занят"); return(View(userVM)); } } using (ChekitDB chekitDB = new ChekitDB()) { UsersDTO usersDTO = await chekitDB.Users.FindAsync(userId); usersDTO.Login = userVM.Login; usersDTO.Email = userVM.Email; usersDTO.Password = usersDTO.Password; usersDTO.AvatarName = userVM.AvatarName; await chekitDB.SaveChangesAsync(); } TempData["OK"] = "Профиль отредактирован"; #region Image Upload if (file != null && file.ContentLength > 0) { string extension = file.ContentType.ToLower(); string[] extensions = { "image/jpg", "image/jpeg", "image/gif", "image/png" }; int counter = 0; //Проверяем расширение файла foreach (var item in extensions) { if (extension != item) { counter++; if (counter == extensions.Length) { using (ChekitDB chekitDB = new ChekitDB()) { ModelState.AddModelError("", "Изображение не было загружено - неправильный формат изображения"); return(View(userVM)); } } } } var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Avatars\\Uploads")); var pathString1 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + userId.ToString()); var pathString2 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + userId.ToString() + "\\Thumbs"); DirectoryInfo directoryInfo1 = new DirectoryInfo(pathString1); DirectoryInfo directoryInfo2 = new DirectoryInfo(pathString2); foreach (var item in directoryInfo1.GetFiles()) { item.Delete(); } foreach (var item in directoryInfo2.GetFiles()) { item.Delete(); } string avatarName = file.FileName; using (ChekitDB chekitDB = new ChekitDB()) { UsersDTO usersDTO = await chekitDB.Users.FindAsync(userId); usersDTO.AvatarName = avatarName; await chekitDB.SaveChangesAsync(); } var pathOriginalAvatar = string.Format($"{pathString1}\\{avatarName}"); var pathLittleAvatar = string.Format($"{pathString2}\\{avatarName}"); file.SaveAs(pathOriginalAvatar); WebImage littleAvatar = new WebImage(file.InputStream); littleAvatar.Resize(150, 150); littleAvatar.Save(pathLittleAvatar); } #endregion return(RedirectToAction("Index")); }
public void AddImageWatermarkDoesNotChangeWatermarkImage() { WebImage watermark = new WebImage(_BmpImageBytes); WebImage image = new WebImage(_JpgImageBytes); image.AddImageWatermark(watermark, width: 54, height: 22, horizontalAlign: "LEFT", verticalAlign: "top", opacity: 50, padding: 10); Assert.Equal(108, watermark.Width); Assert.Equal(44, watermark.Height); }
public void AddImageWatermarkThrowsOnNullImage() { WebImage image = new WebImage(_JpgImageBytes); Assert.ThrowsArgumentNull( () => image.AddImageWatermark(watermarkImage: null), "watermarkImage"); }
public void AddImageWatermarkThrowsWhenOpacityIsIncorrect() { WebImage watermark = new WebImage(_BmpImageBytes); WebImage image = new WebImage(_JpgImageBytes); Assert.ThrowsArgumentOutOfRange(() => image.AddImageWatermark(watermark, opacity: -1), "opacity", "Value must be between 0 and 100."); Assert.ThrowsArgumentOutOfRange(() => image.AddImageWatermark(watermark, opacity: 120), "opacity", "Value must be between 0 and 100."); }
public static void GetFull_ThumpImages(string Source, Stream _stream, string ContentType, out WebImage fullsize, out WebImage thumbs, out byte[] stream) { fullsize = null; thumbs = null; stream = ReadFully(_stream); if (Source == "EmployeePic") { fullsize = new WebImage(stream).Resize(180, 180); thumbs = new WebImage(stream).Resize(32, 32); } else if (Source == "CompanyLogo") { fullsize = new WebImage(stream).Resize(396, 130); thumbs = new WebImage(stream).Resize(80, 80); } else if (ContentType != "application/pdf") { fullsize = new WebImage(stream).Resize(1240, 1754); // 1240, 1754 2480, 3508 thumbs = new WebImage(stream).Resize(124, 175); } else if (ContentType == "application/pdf") { // do nothing } else { fullsize = new WebImage(stream).Resize(1240, 1754); thumbs = new WebImage(stream).Resize(80, 80); } }
/// <summary> /// Web上からテクスチャを取得する。 /// キャッシュにあれば、キャッシュから返す /// </summary> /// <param name="url"></param> /// <returns></returns> public IEnumerator GetWebTexutre(string url) { //ディクショナリ存在チェック if (DicImage.ContainsKey(url)) { //ファイルパス取得 string filePath = DicImage[url].FilePath; //ファイルパスが空の場合は、NULL if (filePath == "" || filePath == DOWNLOAD_NOW) { yield return(GetNoImageTex()); goto End; } //存在チェック if (File.Exists(filePath)) { //ディクショナリからファイルパスを取得する yield return(TextureUtil.GetTextureFromFile(filePath)); goto End; } } else { //とりあえず登録 this.Add(new DatImageFileInfo(url, DOWNLOAD_NOW, DateTime.Now)); } //ファイル名、ファイルパス生成 string path = CreateFilePath(url); //ファイル名取得失敗時 if (path != "") { //最新ニュースデータ取得 var Async = WebImage.GetImage(url); //非同期実行 yield return(Async); //データ取得 Texture2D texture = (Texture2D)Async.Current; if (texture != null) { try { if (!texture.isBogus()) { //PNGで保存 TextureUtil.SavePng(texture, path); //辞書に登録 this.Add(new DatImageFileInfo(url, path, DateTime.Now)); } else { //ノーイメージをセット texture = GetNoImageTex(); //辞書に登録 this.Add(new DatImageFileInfo(url, "", DateTime.Now)); } } catch { Debug.Log("ファイル保存失敗:" + url); } } else { //ノーイメージをセット texture = GetNoImageTex(); //辞書に登録 this.Add(new DatImageFileInfo(url, "", DateTime.Now)); } //セーブ Save(); //取得したテクスチャを返す yield return(texture); } else { //空を返す yield return(null); } End :; }
public ActionResult AddStudent(StudentVM model, HttpPostedFileBase file) { if (!ModelState.IsValid) { using (Db db = new Db()) { model.Cohorts = new SelectList(db.Cohorts.ToList(), "Id", "Name"); return(View(model)); } } using (Db db = new Db()) { if (db.Student.Any(x => x.FirstName == model.FirstName)) { model.Cohorts = new SelectList(db.Cohorts.ToList(), "Id", "Name"); ModelState.AddModelError("", "Sorry! That student name is taken!"); return(View(model)); } } int id; using (Db db = new Db()) { StudentDTO student = new StudentDTO(); student.FirstName = model.FirstName; student.LastName = model.LastName; student.Root = model.FirstName.Replace(" ", "-").ToLower(); student.CohortId = model.CohortId; CohortDTO catDTO = db.Cohorts.FirstOrDefault(x => x.Id == model.CohortId); student.CohortName = catDTO.Name; db.Student.Add(student); //db.SaveChanges(); id = student.Id; } TempData["SM"] = "Successfully added a student!"; #region Upload Image var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } if (file != null && file.ContentLength > 0) { string ext = file.ContentType.ToLower(); if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Cohorts = new SelectList(db.Cohorts.ToList(), "Id", "Name"); ModelState.AddModelError("", "ERROR: The image was not uploaded - wrong image extension."); return(View(model)); } } string imageName = file.FileName; using (Db db = new Db()) { StudentDTO dto = db.Student.Find(id); if (dto != null) { dto.ImageName = imageName; } db.SaveChanges(); } var path = string.Format("{0}\\{1}", pathString2, imageName); var path2 = string.Format("{0}\\{1}", pathString3, imageName); file.SaveAs(path); WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion return(RedirectToAction("AddStudent")); }
public ActionResult Register([Bind(Include = "MerchantID,Email,MatKhauMaHoa,HoTen,DiaChi,GioiTinhID,TenCuaHang,SoDienThoai")] Merchant merchant, string AuthenticationCode, HttpPostedFileBase imageAvatar) { //check Ho ten if (merchant.HoTen.Trim().Any(char.IsNumber)) { ViewBag.GioiTinhID = new SelectList(db.GioiTinhs, "GioiTinhID", "TenGioiTinh", "1"); ModelState.AddModelError("", "Họ tên không hợp lệ!"); return(View(merchant)); } //check password if (merchant.MatKhauMaHoa.Trim().Length < 5) { ViewBag.GioiTinhID = new SelectList(db.GioiTinhs, "GioiTinhID", "TenGioiTinh", "1"); ModelState.AddModelError("", "Mật khẩu không hợp lệ! Mật khẩu hợp lệ phải chứa ít nhất 5 ký tự bao gồm chữ và số"); return(View(merchant)); } if (merchant.MatKhauMaHoa.Trim().All(char.IsLetter)) { ViewBag.GioiTinhID = new SelectList(db.GioiTinhs, "GioiTinhID", "TenGioiTinh", "1"); ModelState.AddModelError("", "Mật khẩu không hợp lệ! Mật khẩu hợp lệ phải chứa ít nhất 1 ký tự số và chữ"); return(View(merchant)); } var authenticationEmail = (AuthenticationEmail)Session[CommonConstants.AUTHENTICATIONEMAILMERCHANT_SESSION]; if (ModelState.IsValid & authenticationEmail != null) { if (merchant.Email == authenticationEmail.Email & authenticationEmail.AuthenticationCode == AuthenticationCode) { merchant.MatKhauMaHoa = Encryptor.SHA256Encrypt(merchant.MatKhauMaHoa); merchant.TrangThai = false; merchant.NgayTao = System.DateTime.Now; merchant.SoLuongKIPXu = 0; db.Merchants.Add(merchant); db.SaveChanges(); if (imageAvatar != null) { //Resize Image WebImage img = new WebImage(imageAvatar.InputStream); //img.Resize(500, 1000); var filePathOriginal = Server.MapPath("/Assets/Image/Merchant/"); var fileName = merchant.MerchantID + ".jpg"; string savedFileName = Path.Combine(filePathOriginal, fileName); img.Save(savedFileName); } Session[CommonConstants.USERMERCHANT_SESSION] = null; return(RedirectToAction("MerchantRegSuccess", "Home", new { area = "" })); } else { ViewBag.GioiTinhID = new SelectList(db.GioiTinhs, "GioiTinhID", "TenGioiTinh"); ModelState.AddModelError("", "Mã xác thực không hợp lệ"); return(View(merchant)); } } ViewBag.GioiTinhID = new SelectList(db.GioiTinhs, "GioiTinhID", "TenGioiTinh", 1); return(View(merchant)); }
public void AddImageWatermarkThrowsWhenJustOneDimensionIsZero() { WebImage watermark = new WebImage(_BmpImageBytes); WebImage image = new WebImage(_JpgImageBytes); string message = "Watermark width and height must both be positive or both be zero."; Assert.Throws<ArgumentException>( () => image.AddImageWatermark(watermark, width: 0, height: 22), message); Assert.Throws<ArgumentException>( () => image.AddImageWatermark(watermark, width: 100, height: 0), message); }
private void GuardarImagenEnServidor(WebImage image, string path, string fileName) { image.Save(Path.Combine("~" + path + fileName)); image = null; }
public void AddImageWatermarkThrowsOnNegativeDimensions() { WebImage watermark = new WebImage(_BmpImageBytes); WebImage image = new WebImage(_JpgImageBytes); Assert.ThrowsArgumentGreaterThanOrEqualTo( () => image.AddImageWatermark(watermark, width: -1), "width", "0"); Assert.ThrowsArgumentGreaterThanOrEqualTo( () => image.AddImageWatermark(watermark, height: -1), "height", "0"); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) //caters for uploaed image named file in AddProduct view { //check model state if (!ModelState.IsValid) { // populate categories property in the product model model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } //Make sure product name is unique //check if its unique if (db.Products.Any(x => x.Name == model.Name)) { //if there's a match model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That product name is taken"); return(View(model)); } //Declare Product id int id; //Init and save productDTO Product product = new Product(); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.CategoryId = model.CategoryId; //Also need to get categories name using the categoires DTO Category catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); //for categories selectList product.CategoryName = catDTO.Name; //add dto db.Products.Add(product); db.SaveChanges(); //get id of primary key of row just inserted id = product.Id; //Set TempData message TempData["SM"] = "You have added a product!"; #region Upload Image //code create necessary directories not done mannually var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); //another folder var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); // creates another folder var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thubs"); //creates another folder for thubs var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); //creates another folder for gallery images var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thubs"); //creats another folder for gallery images if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } //Check if file was uploaded if (file != null && file.ContentLength > 0) { //Get file extensions string ext = file.ContentType.ToLower(); //Verify extension if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjeg" && ext != "image/x-png" && ext != "image/png") { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded -wrong image extension"); return(View(model)); } //Intitilase image name string imageName = file.FileName; //Save image name to DTO Product dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); //Set original and thub image paths# var path = string.Format("{0}\\{1}", pathString2, imageName); var path2 = string.Format("{0}\\{1}", pathString3, imageName); //save original image file.SaveAs(path); //create and save thub WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion //Redirect return(RedirectToAction("AddProduct")); }
public void AddImageWatermarkThrowsOnIncorrectVerticalAlignment() { WebImage watermark = new WebImage(_BmpImageBytes); WebImage image = new WebImage(_JpgImageBytes); Assert.Throws<ArgumentException>( () => image.AddImageWatermark(watermark, verticalAlign: "vertical"), "The \"verticalAlign\" value is invalid. Valid values are: \"Top\", \"Bottom\", and \"Middle\"."); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { //Проверяем модель на валидность if (!ModelState.IsValid) { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } } //Проверяем продукт на уникальность using (Db db = new Db()) { if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "Данный продукт уже создан!"); return(View(model)); } } //Объявляем переменную ProductId int id; //Инициализируем и сохранчемм модель на основе ProductDTO using (Db db = new Db()) { ProductDTO product = new ProductDTO(); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Color = model.Color; product.Memory = model.Memory; product.Price = model.Price; product.CategoryId = model.CategoryId; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); product.CategoryName = catDTO.Name; db.Products.Add(product); db.SaveChanges(); id = product.Id; } //Добавляем сообщение в TempData TempData["SM"] = "Продукт добавлен!"; //работа с загрузкой изображения #region UploadImage // Создаем необходимые ссылки на дериктории var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); //Проверяем наличие дириктории if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } //Проверяем загружен ли файл if (file != null && file.ContentLength > 0) { //Получаем расширение файла string ext = file.ContentType.ToLower(); //Проверяем расширение if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "Изображение не было загружено - не верный формат файла!"); return(View(model)); } } //Объявляем переменную с имененем изображения string imageName = file.FileName; //Сохраняем имя изображения в модель DTO using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } //Назначаем пути к оригинальному и уменьшиному изображению var path = string.Format($"{pathString2}\\{imageName}"); var path2 = string.Format($"{pathString3}\\{imageName}"); //Сохраняем оригинальное изображение file.SaveAs(path); //Создаем и сохраняем уменьшиную копию WebImage img = new WebImage(file.InputStream); img.Resize(200, 200).Crop(1, 1); img.Save(path2); } #endregion //Переадрисовываем пользователя return(RedirectToAction("AddProduct")); }
public void AddImageWatermarkDoesNotChangeImageIfWatermarkIsTooBig() { WebImage watermark = new WebImage(_JpgImageBytes); WebImage image = new WebImage(_BmpImageBytes); byte[] originalBytes = image.GetBytes("jpg"); // This will use original watermark image dimensions which is bigger than the target image. image.AddImageWatermark(watermark); byte[] watermarkedBytes = image.GetBytes("jpg"); Assert.Equal(originalBytes, watermarkedBytes); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { //Получить ID int id = model.Id; //Заполнить список категориями и изображениями using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } model.GalleryImages = Directory .EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")) .Select(fn => Path.GetFileName(fn)); //Проверка модели на валидность if (!ModelState.IsValid) { return(View(model)); } //Проверка продукта на уникальность using (Db db = new Db()) { if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "Имя продукта занято"); return(View(model)); } } //Обновить продукт в БД using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Color = model.Color; dto.Memory = model.Memory; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.ImageName = model.ImageName; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = catDTO.Name; db.SaveChanges(); } //Установить сообщение в ТемпДата TempData["SM"] = "Продукт обновлен"; //загрузка изображения #region ImageUpload //Проверяем загрузку файла if (file != null && file.ContentLength > 0) { //Получаем расширение файла string ext = file.ContentType.ToLower(); //Проверяем расширение if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { ModelState.AddModelError("", "Изображение не было загружено - не верный формат файла!"); return(View(model)); } } //Устанавливаем пути загрузки var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); //Удаляем существующие файлы и директории DirectoryInfo di1 = new DirectoryInfo(pathString1); DirectoryInfo di2 = new DirectoryInfo(pathString2); foreach (var file2 in di1.GetFiles()) { file2.Delete(); } foreach (var file3 in di2.GetFiles()) { file3.Delete(); } //Сохраняем изображение string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } //Сохраняем оригинал и превью версии var path = string.Format($"{pathString1}\\{imageName}"); var path2 = string.Format($"{pathString2}\\{imageName}"); //Сохраняем оригинальное изображение file.SaveAs(path); //Создаем и сохраняем уменьшиную копию WebImage img = new WebImage(file.InputStream); img.Resize(200, 200).Crop(1, 1); img.Save(path2); } #endregion //Переадресовать пользователя на представление return(RedirectToAction("EditProduct")); }
public void WebImagePreservesOriginalFormatFromFile() { WebImage image = new WebImage(_PngImageBytes); byte[] returnedContent = image.GetBytes(); // If format was changed; content would be different Assert.Equal(_PngImageBytes, returnedContent); }
public ActionResult AddProduct(ProductViewModel productViewModel, HttpPostedFileBase file) { if (!ModelState.IsValid) { List <DanhMuc> list = db.DanhMucs.ToList(); ViewBag.listDanhMuc = new SelectList(list, "MaDanhMuc", "Ten"); return(View(productViewModel)); } if (db.SanPhams.Any(x => x.Ten == productViewModel.Ten)) { //List<DanhMuc> list = db.DanhMucs.ToList(); //ViewBag.listDanhMuc = new SelectList(list, "MaDanhMuc", "Ten"); ModelState.AddModelError("", "Tên sản phẩm đã tồn tại"); return(View(productViewModel)); } int id; SanPham sanPham = new SanPham(); sanPham.Ten = productViewModel.Ten; sanPham.Slug = productViewModel.Slug; sanPham.MoTa = productViewModel.MoTa; sanPham.Gia = productViewModel.Gia; sanPham.SoLuongTon = productViewModel.SoLuongTon; sanPham.Available = productViewModel.Available; sanPham.MaDanhMuc = productViewModel.MaDanhMuc; db.SanPhams.Add(sanPham); db.SaveChanges(); id = sanPham.MaSanPham; TempData["Message"] = "Sản phẩm thêm thành công"; #region upload image //create directories var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathstring1 = Path.Combine(originalDirectory.ToString(), "SanPhams"); var pathstring2 = Path.Combine(originalDirectory.ToString(), "SanPhams" + id.ToString()); var pathstring3 = Path.Combine(originalDirectory.ToString(), "SanPhams" + id.ToString() + "\\Thumbs"); var pathstring4 = Path.Combine(originalDirectory.ToString(), "SanPhams" + id.ToString() + "\\Gallery"); var pathstring5 = Path.Combine(originalDirectory.ToString(), "SanPhams" + id.ToString() + "\\Gallery\\Thumbs"); if (!Directory.Exists(pathstring1)) { Directory.CreateDirectory(pathstring1); } if (!Directory.Exists(pathstring2)) { Directory.CreateDirectory(pathstring2); } if (!Directory.Exists(pathstring3)) { Directory.CreateDirectory(pathstring3); } if (!Directory.Exists(pathstring4)) { Directory.CreateDirectory(pathstring4); } if (!Directory.Exists(pathstring5)) { Directory.CreateDirectory(pathstring5); } if (file != null && file.ContentLength > 0) { string ext = file.ContentType.ToLower(); if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { ModelState.AddModelError("", "Hình ảnh upload không thành công"); return(View(productViewModel)); } string imagename = file.FileName; sanPham = db.SanPhams.Find(id); sanPham.Hinh = imagename; db.SaveChanges(); var path = string.Format("{0}\\{1}", pathstring2, imagename); var path2 = string.Format("{0}\\{1}", pathstring3, imagename); file.SaveAs(path); WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } db.SaveChanges(); #endregion return(RedirectToAction("AddProduct")); }
public void AddImageWatermarkWithFileNameThrowsExceptionWhenWatermarkFilePathIsEmpty() { var context = GetContext(); WebImage image = new WebImage(_BmpImageBytes); Assert.ThrowsArgument( () => image.AddImageWatermark(context, s => _JpgImageBytes, watermarkImageFilePath: null, width: 0, height: 0, horizontalAlign: "Right", verticalAlign: "Bottom", opacity: 100, padding: 5), "filePath", "Value cannot be null or an empty string."); }
public ActionResult EditClient(ClientVM model, HttpPostedFileBase file) { //Получаем ID заявки будем использоовать для работы с изображением int id = model.Id; //Список изображений //Получаем все изображения из галереи model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Clients/" + id + "/Thumds")) .Select(fn => Path.GetFileName(fn)); //проверяем модель на валидность if (!ModelState.IsValid) { return(View(model)); } #region поиск имени на уникальность //using(DBContext db = new DBContext()) //{ // //ищем В выборке все id кроме текущего. Проверяем на совпадения по фамилии // if (db.clients.Where(x => x.Id != id).Any(x=> x.lastName == model.LastName)) // { // //ModelState.AddModelError("","Данный клиент уже подовал заявку") // return View(model); // //можно в дальнейшем реализовать историю заявок конкретного клиента // } //} #endregion //обновляем продукт using (DBContext db = new DBContext()) { //Загружаем старые(необновленные) данные заявки в БД Client dto = db.clients.Find(id); dto.firstName = model.FirstName; dto.lastName = model.LastName; dto.middleName = model.MiddleName; dto.birthDate = model.BirthDate; dto.dateRequest = DateTime.Now.ToString(); dto.email = model.Email; dto.image = model.Image; db.SaveChanges(); } //устанавливаем сообщение в темп дату //Сообщение пользователю. с помощью темп дата TempData["SM"] = "Заявка успешно отредактирована!"; //загружаем обработанно изображение //ЗАГРУЗКА ИЗАБРАЖЕНИЯ #region Загрузка изображения на сервер // проверяем загружен ли файл if (file != null && file.ContentLength > 0) { //получить разширение файла string ext = file.ContentType.ToLower(); // проверяем полученное разшерение файла if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/png" && ext != "image/x-png") { using (DBContext db = new DBContext()) { //model. ModelState.AddModelError("", "Не коректный формат !! Изображение не было загружено!"); //Сообщение пользователю. с помощью темп дата TempData["SM"] = "Заявка успешно оформлена! Но без изображения!!!"; return(View(model)); } } //устанавливаем пути загрузки // создание ссылок дирикторий(папок для картинки). Корневая папка var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); var originalDirectory2 = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Archive_Documents\\DocsClient")); ////путь к папке и кажому новому клиенту(по id). var pathString1 = Path.Combine(originalDirectory.ToString(), "Clients\\" + id.ToString()); //Путь к папка для хранения уменьшеной копии var pathString2 = Path.Combine(originalDirectory.ToString(), "Clients\\" + id.ToString() + "\\Thumds"); // папки хранения документов Ворд var pathString3 = Path.Combine(originalDirectory2.ToString(), id.ToString()); // папки хранения документов PDF var pathString4 = Path.Combine(originalDirectory2.ToString(), id.ToString()); //удаляем существуешие старые файлы и директории. DirectoryInfo dir1 = new DirectoryInfo(pathString1); DirectoryInfo dir2 = new DirectoryInfo(pathString2); DirectoryInfo dir3 = new DirectoryInfo(pathString3); DirectoryInfo dir4 = new DirectoryInfo(pathString4); //Удаляем подпапки foreach (var file2 in dir1.GetFiles()) { file2.Delete(); } foreach (var file3 in dir2.GetFiles()) { file3.Delete(); } foreach (var file4 in dir3.GetFiles()) { file4.Delete(); } foreach (var file5 in dir4.GetFiles()) { file5.Delete(); } ////сохраняем изображение string imageName = file.FileName; int idDocWord = id; //сохраняемм оригинал и превью картинки //Назначить пути к оригинальному и уменьшеному изабражению var path = string.Format($"{pathString1}\\{imageName}"); var path2 = string.Format($"{pathString2}\\{imageName}"); // уменьшенное изображене var path3 = string.Format($"{pathString2}\\{idDocWord}"); // уменьшенное изображене //сохранить оригинальное изображение file.SaveAs(path); //создаем и сохраняем уменьшенную копиию //обьект WebImage позволяет работать с изображениями WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); //Ширина, высота сохраненного изображения. img.Save(path2); // Куда сохраняем уменьшенное изображение img.Save(path3); // Куда сохраняем уменьшенное изображение для документа using (DBContext db = new DBContext()) { string tempPath = $"{path3}\\{imageName}"; Client dto = db.clients.Find(id); dto.image = imageName; dto.imagePathInDoc = tempPath; // сохраняем путь к файлу db.SaveChanges(); //save DB } } #endregion workingWord = new WorkingWord(); // создание ссылок дирикторий(папок для документов). Корневая папка var originalDirectoryWordDoc = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Archive_Documents\\")); //Создается папка дл хранения дока var pathString6 = Path.Combine(originalDirectoryWordDoc.ToString(), "DocsClient\\" + id.ToString() + "\\Document\\"); // путь к самому документу string TestSaveDoc = $@"{pathString6}Result_Client_{id}.pdf"; //Создание отредактированых документов. CreateDocWordOfPdf(id); //Переодрeсовать пользователя return(RedirectToAction("EditClient")); }
public void SaveOverwritesExistingFile() { Action<string, byte[]> saveAction = (path, content) => { }; WebImage image = new WebImage(_BmpImageBytes); string newFileName = @"x:\newImage.bmp"; image.Save(GetContext(), saveAction, newFileName, imageFormat: null, forceWellKnownExtension: true); image.RotateLeft(); // just verify this does not throw image.Save(GetContext(), saveAction, newFileName, imageFormat: null, forceWellKnownExtension: true); }
public ActionResult AddNewClient(ClientVM model, HttpPostedFileBase file) { //проверяем модель на валидность. if (!ModelState.IsValid) { return(View(model)); // Возращаем модель на форму } //проверка имени на уникальность using (DBContext db = new DBContext()) { //РПроверяем. Есть ли такое имя в БД if (db.clients.Any(x => x.firstName == model.FirstName)) { //Данное умя уже содержится в БД // ModelState.AddModelError("", "Данное имя не уникально!! ВВедите другое"); // return View(file); // Возращаем модель на форму } } //переменная для client ID int id; //иницализируем и сохраняем модель на основе клиента ДТО using (DBContext db = new DBContext()) { Client clientDto = new Client(); //присваиваем имя клиента в большом регистре модели. clientDto.firstName = model.FirstName.ToUpper(); clientDto.lastName = model.LastName.ToUpper(); clientDto.middleName = model.MiddleName.ToUpper(); //День рождения и сумма заявки clientDto.birthDate = model.BirthDate; clientDto.loanSum = model.LoanSum; //Присваиваем оставщися знчения модели. DateTime date1 = DateTime.Now; clientDto.dateRequest = date1.ToString("d"); clientDto.email = model.Email; //сохраняем модель в БД db.clients.Add(clientDto); db.SaveChanges(); id = clientDto.Id; } // ЗАГРУЗКА ФАЙЛА #region Загрузка файла // создание ссылок дирикторий(папок для картинки). Корневая папка var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); var originalDirectory2 = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Archive_Documents\\")); ////Создается папка к кажому новому клиенту(по id). var pathString1 = Path.Combine(originalDirectory.ToString(), "Clients"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Clients\\" + id.ToString()); //Создается папка дл хранения уменьшеной копии var pathString3 = Path.Combine(originalDirectory.ToString(), "Clients\\" + id.ToString() + "\\Thumds"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Clients\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Clients\\" + id.ToString() + "\\Gallery\\Thumds"); //Создается папка дл хранения уменьшеной копии var pathString6 = Path.Combine(originalDirectory2.ToString(), "DocsClient\\" + id.ToString() + "\\Document"); //Проверяем наличие директории (если нет, создаем) if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } if (!Directory.Exists(pathString6)) { Directory.CreateDirectory(pathString6); } //Проверяем был ли файл загружен. if (file != null && file.ContentLength > 0) { // Получаем разширение файла ContentType получаем тип передоваемого файла string ext = file.ContentType.ToLower(); // проверяем разширение файла if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/png" && ext != "image/x-png") { using (DBContext db = new DBContext()) { //model. ModelState.AddModelError("", "Не коректный формат !! Изображение не было загружено!"); //Сообщение пользователю. с помощью темп дата TempData["SM"] = "Заявка успешно оформлена! Но без изображения!!!"; return(View(model)); } } //переменная для хранения имени изображения string imageName = file.FileName; int idDocWord = id; string docPdf = $@"\\Result_Client_{idDocWord.ToString()}.pdf";; //Назначить пути к оригинальному и уменьшеному изабражению var path = string.Format($"{pathString2}\\{imageName}"); var path2 = string.Format($"{pathString3}\\{imageName}"); // уменьшенное изображене var path3 = string.Format($"{pathString3}"); // уменьшенное изображене //сохранить оригинальное изображение file.SaveAs(path); //создаем и сохраняем уменьшенную копиию //обьект WebImage позволяет работать с изображениями WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); //Ширина, высота сохраненного изображения. img.Save(path2); // Куда сохраняем уменьшенное изображение img.Save(path3); // Куда сохраняем уменьшенное изображение для документа //сохранить изображение в модель DTO using (DBContext db = new DBContext()) { string tempPath = $"{path3}\\{imageName}"; string tempPathPDf = $"{pathString6}\\{imageName}"; Client dto = db.clients.Find(idDocWord); dto.image = imageName; dto.imagePathInDoc = tempPath; // сохраняем путь к файлу dto.pdfPathInDoc = docPdf; //имя файла // создания файла пдв и док CreateDocWordOfPdf(id); // dto.pdfPathInDoc = db.SaveChanges(); } } #endregion //Сообщение пользователю. с помощью темп дата TempData["SM"] = "Заявка успешно оформлена!"; CreateDocWordOfPdf(id); // создаем 2 типа докуентов. Word и Pdf //переодрисовать пользователя return(RedirectToAction("GetAllClients")); }
public void SaveThrowsWhenPathIsEmpty() { Action<string, byte[]> saveAction = (path, content) => { }; WebImage image = new WebImage(_BmpImageBytes); Assert.ThrowsArgumentNullOrEmptyString( () => image.Save(GetContext(), saveAction, filePath: String.Empty, imageFormat: null, forceWellKnownExtension: true), "filePath"); }
public void SetUserIcon(WebImage icon) { userCharacterModelsUserIcon.Load(icon); }
public void WebImagePreservesOriginalFormatFromStream() { WebImage image = null; byte[] originalContent = _PngImageBytes; using (MemoryStream stream = new MemoryStream(originalContent)) { image = new WebImage(stream); } // dispose stream; WebImage should have no dependency on it byte[] returnedContent = image.GetBytes(); // If format was changed; content would be different Assert.Equal(originalContent, returnedContent); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { // Check model state if (!ModelState.IsValid) { using (ApplicationDbContext db = new ApplicationDbContext()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } } // Make sure product name is unique using (ApplicationDbContext db = new ApplicationDbContext()) { if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } // Declare product id int id; // Init and save productDTO using (ApplicationDbContext db = new ApplicationDbContext()) { ProductDTO product = new ProductDTO(); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.CategoryId = model.CategoryId; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); product.CategoryName = catDTO.Name; db.Products.Add(product); db.SaveChanges(); // Get the id id = product.Id; } // Set TempData message TempData["SM"] = "You have added a product!"; #region Upload Image // Create necessary directories var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } // Check if a file was uploaded if (file != null && file.ContentLength > 0) { // Get file extension string ext = file.ContentType.ToLower(); // Verify extension if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (ApplicationDbContext db = new ApplicationDbContext()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded - wrong image extension."); return(View(model)); } } // Init image name string imageName = file.FileName; // Save image name to DTO using (ApplicationDbContext db = new ApplicationDbContext()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } // Set original and thumb image paths var path = string.Format("{0}\\{1}", pathString2, imageName); var path2 = string.Format("{0}\\{1}", pathString3, imageName); // Save original file.SaveAs(path); // Create and save thumb WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion // Redirect return(RedirectToAction("AddProduct")); }
/// <summary> /// Spracuje request poziadavku na nacitanie obrazku /// </summary> /// <param name="context">HttpContext</param> public void ProcessRequest(HttpContext context) { //nazov suboru String baseUrl = context.Request.RawUrl; String file = baseUrl.Replace(WebConfiguration.ImageConfiguration.BasUrl, String.Empty); Nullable<Guid> key = null; Nullable<int> width = null; Nullable<int> height = null; if (this.internalParseImageUrl(ref file, out key, out width, out height)) { //update file name file = !width.HasValue && !height.HasValue ? String.Format("{0}.data", key.Value.ToStringWithoutDash()) : String.Format("{0}_{1}_{2}.data", key.Value.ToStringWithoutDash(), (width.HasValue ? width.Value : 0), (height.HasValue ? height.Value : 0)); //ziskame format obrazku ImageFormat format = this.InternalGetContentType(baseUrl); String directory = context.Server.MapPath(WebImageHandler.m_directoryPath); file = context.Server.MapPath(String.Format("{0}{1}", WebImageHandler.m_directoryPath, file)); WebImage image = null; if (File.Exists(file)) { image = new WebImage(System.IO.File.ReadAllBytes(file), format); } else { if (WebConfiguration.OnImageLoadDelegate != null) { image = WebConfiguration.OnImageLoadDelegate(key.Value, format); if (image != null) { if (width.HasValue) { image.Image = image.Image.CropOrResizeImage(width, height, format); } try { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllBytes(file, image.ImageBlob); } catch (Exception ex) { Debug.WriteLine(ex); } } } } if (image != null) { context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.Cache.SetMaxAge(new TimeSpan(2, 0, 0, 0)); context.Response.ContentType = image.ContentType; context.Response.BinaryWrite(image.ImageBlob); return; } } context.Response.StatusCode = 404; context.Response.StatusDescription = "Image not found !"; }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { //Получение id продукта int id = model.Id; //Заполнение списка ктегориями и изображениями using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } model.GalleryImages = Directory .EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Small")) .Select(fn => Path.GetFileName(fn)); //Проверка модели на валидность if (!ModelState.IsValid) { return(View(model)); } //Проверка имени продукта на уникальность using (Db db = new Db()) { if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "Это название рекламы занято"); return(View(model)); } } //Обновление продукта using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.ImageName = model.ImageName; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); //Присваивание текущей категории модели dto.CategoryName = catDTO.Name; db.SaveChanges(); } //Установка сообщения в TempData TempData["M"] = "Вы изменили рекламу"; //Логика обработки изображений #region Image Upload //Проверка загрузки файла if (file != null && file.ContentLength > 0) { //Получение расширения файла string ext = file.ContentType.ToLower(); //Проверка расширения if (ext != "image/jpg" && ext != "image/png" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png") { using (Db db = new Db()) { ModelState.AddModelError("", "Картинка не загружена. Недопустимое расширение."); return(View(model)); } } //Установка путей загрузки var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Small"); //Удаление существующих путей и директорий DirectoryInfo di1 = new DirectoryInfo(pathString1); DirectoryInfo di2 = new DirectoryInfo(pathString2); //удаление в основной директории foreach (var file2 in di1.GetFiles()) { file2.Delete(); } //Удаление цменьшенных изображений foreach (var file3 in di1.GetFiles()) { file3.Delete(); } //Сохранение имени изображения string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } //Сохранение оригинала и уменьшенной версии var path = string.Format($"{pathString1}\\{imageName}"); //к оригинальному изображению var path2 = string.Format($"{pathString2}\\{imageName}"); //к уменьшенному //Сохранение оригинального изображения file.SaveAs(path); //Создание и сохранение уменьшенной картинки WebImage img = new WebImage(file.InputStream); img.Resize(200, 200).Crop(1, 1); img.Save(path2); } #endregion //Переадресация пользователя return(RedirectToAction("EditProduct")); }