public HttpResponseMessage GetThumbnail(string imagePath, int width) { if (false == string.IsNullOrWhiteSpace(imagePath) && imagePath.IndexOf("{{") < 0) { var image = Image.FromFile(System.Web.Hosting.HostingEnvironment.MapPath(imagePath)); MemoryStream outStream = new MemoryStream(); byte[] photoBytes = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath(imagePath)); // change imagePath with a valid image path ISupportedImageFormat format = new JpegFormat { Quality = 70 }; // convert to jpg var inStream = new MemoryStream(photoBytes); var imageFactory = new ImageFactory(preserveExifData: true); Size size = ResizeKeepAspect(image.Size, width, width); ResizeLayer resizeLayer = new ResizeLayer(size, ResizeMode.Max); imageFactory.Load(inStream) .Resize(resizeLayer) .Format(format) .Save(outStream); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(outStream); response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png"); return response; } else { return null; } }
private static async Task<Tuple<Stream, Image>> ImageResize(string imageString, int quality, Func<System.Drawing.Image, Size> sizeCalculation) { var photoBytes = Base64ImageDataToByteArray(imageString); var format = new JpegFormat(); using (MemoryStream inStream = new MemoryStream(photoBytes)) { MemoryStream outStream = new MemoryStream(); int width; int height; using (ImageFactory imageFactory = new ImageFactory()) { imageFactory.Load(inStream) .Resize(sizeCalculation(imageFactory.Image)) .Format(format) .Quality(quality); System.Drawing.Image image = imageFactory.Image; width = image.Width; height = image.Height; imageFactory.Save(outStream); } return new Tuple<Stream, Models.Image>(outStream, new Image("bloblstorage", width, height)); // Do something with the stream. } }
/// <summary> /// Method used to crop image. /// </summary> /// <param name="inputImagePathString">input image path</param> /// <param name="outputImagePathName">ouput image path</param> /// <param name="x1">x</param> /// <param name="y1">y</param> /// <param name="width">widht of cropped image</param> /// <param name="height">height of cropped image</param> public static void CropImage(string inputImagePathString, String outputImagePathName, int x1, int y1, int width, int height) { byte[] photoBytes = File.ReadAllBytes(inputImagePathString); // Format is automatically detected though can be changed. ISupportedImageFormat format = new JpegFormat { Quality = 70 }; Rectangle rectangle = new Rectangle(x1, y1, width, height); using (MemoryStream inStream = new MemoryStream(photoBytes)) { using (MemoryStream outStream = new MemoryStream()) { // Initialize the ImageFactory using the overload to preserve EXIF metadata. using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true)) { // Load, resize, set the format and quality and save an image. imageFactory.Load(inStream) .Crop(rectangle) .Format(format) .Save(outStream); FileStream fileStream = new FileStream(outputImagePathName, FileMode.Create); outStream.WriteTo(fileStream); fileStream.Close(); } // Do something with the stream. outStream.Close(); } } }
public static ISupportedImageFormat DetectFormat(this MediaTypes mediaType, int quality = Quality) { ISupportedImageFormat result; switch (mediaType) { case MediaTypes.JPG: result = new JpegFormat(); break; case MediaTypes.PNG: result = new PngFormat(); break; default: throw new NotSupportedException($"Not Support MediaType: {mediaType}"); } result.Quality = quality; return result; }
private static byte[] GetandResizeImage(string filePath) { var size = new Size(1024, 683);//RM Spec states 3:2 ratio max size 1024 var format = new JpegFormat { Quality = 90 }; using (var webClient = new WebClient()) { using (MemoryStream inStream = new MemoryStream(webClient.DownloadData(filePath)), outStream = new MemoryStream()) { using (var imageFactory = new ImageFactory()) { // Load, resize, set the format and quality and save an image. imageFactory.Load(inStream) .BackgroundColor(Color.White) .Resize(size) .Format(format) .Save(outStream); } return outStream.ToArray(); } } }
private ISupportedImageFormat GetFormat(string extension, ImageInstruction ins) { ISupportedImageFormat format = null; if (extension.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || extension.Equals(".jpeg", StringComparison.OrdinalIgnoreCase)) format = new JpegFormat { Quality = ins.JpegQuality }; else if (extension.Equals(".gif", StringComparison.OrdinalIgnoreCase)) format = new GifFormat { }; else if (extension.Equals(".png", StringComparison.OrdinalIgnoreCase)) format = new PngFormat { }; return format; }
public async Task<ActionResult> ProfileUpdate(ApplicationUser user, HttpPostedFileBase file) { var userId = User.Identity.GetUserId(); var userExisting = await UserManager.FindByIdAsync(userId); userExisting.FirstName = user.FirstName; userExisting.LastName = user.LastName; userExisting.Gender = user.Gender; userExisting.PhoneNumber = user.PhoneNumber; await UserManager.UpdateAsync(userExisting); if (file != null) { // Format is automatically detected though can be changed. ISupportedImageFormat format = new JpegFormat { Quality = 90 }; Size size = new Size(300, 300); //https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/ // Initialize the ImageFactory using the overload to preserve EXIF metadata. using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true)) { var path = Path.Combine(Server.MapPath("~/images/profile"), string.Format("{0}.{1}", userId, "jpg")); // Load, resize, set the format and quality and save an image. imageFactory.Load(file.InputStream) .Resize(size) .Format(format) .Save(path); } } return RedirectToAction("UserProfile", "Manage"); }
public void SavePicture(HttpPostedFileBase file, string name, Size size, string formatFile = "jpg") { if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName)) { // Format is automatically detected though can be changed. ISupportedImageFormat format = new JpegFormat { Quality = 90 }; if (formatFile == "png") format = new PngFormat() { Quality = 90 }; //https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/ // Initialize the ImageFactory using the overload to preserve EXIF metadata. using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true)) { var path = Path.Combine(Server.MapPath("~/images/community"), string.Format("{0}.{1}", name, formatFile)); // Load, resize, set the format and quality and save an image. imageFactory.Load(file.InputStream) .Resize(size) .Format(format) .Save(path); } } }
public async Task<ActionResult> ListingUpdate(Item item, FormCollection form, IEnumerable<HttpPostedFileBase> files) { bool updateCount = false; int nextPictureOrderId = 0; // Add new listing if (item.ID == 0) { item.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added; item.IP = Request.GetVisitorIP(); item.Expiration = DateTime.MaxValue.AddDays(-1); item.UserID = User.Identity.GetUserId(); updateCount = true; _itemService.Insert(item); } else { // Update listing var itemExisting = await _itemService.FindAsync(item.ID); itemExisting.Title = item.Title; itemExisting.Description = item.Description; itemExisting.CategoryID = item.CategoryID; itemExisting.Enabled = item.Enabled; itemExisting.Active = item.Active; itemExisting.Premium = item.Premium; itemExisting.ContactEmail = item.ContactEmail; itemExisting.ContactName = item.ContactName; itemExisting.ContactPhone = item.ContactPhone; itemExisting.Latitude = item.Latitude; itemExisting.Longitude = item.Longitude; itemExisting.Location = item.Location; itemExisting.ShowPhone = item.ShowPhone; itemExisting.ShowEmail = item.ShowEmail; itemExisting.UserID = item.UserID; itemExisting.Price = item.Price; itemExisting.Currency = item.Currency; itemExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified; _itemService.Update(itemExisting); } // Delete existing fields on item var customFieldItemQuery = await _customFieldItemService.Query(x => x.ItemID == item.ID).SelectAsync(); var customFieldIds = customFieldItemQuery.Select(x => x.ID).ToList(); foreach (var customFieldId in customFieldIds) { await _customFieldItemService.DeleteAsync(customFieldId); } // Get custom fields var customFieldCategoryQuery = await _customFieldCategoryService.Query(x => x.CategoryID == item.CategoryID).Include(x => x.MetaField.ItemMetas).SelectAsync(); var customFieldCategories = customFieldCategoryQuery.ToList(); // Update custom fields foreach (var metaCategory in customFieldCategories) { var field = metaCategory.MetaField; var controlType = (BeYourMarket.Model.Enum.Enum_MetaFieldControlType)field.ControlTypeID; string controlId = string.Format("customfield_{0}_{1}_{2}", metaCategory.ID, metaCategory.CategoryID, metaCategory.FieldID); var formValue = form[controlId]; if (string.IsNullOrEmpty(formValue)) continue; formValue = formValue.ToString(); var itemMeta = new ItemMeta() { ItemID = item.ID, Value = formValue, FieldID = field.ID, ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added }; _customFieldItemService.Insert(itemMeta); } await _unitOfWorkAsync.SaveChangesAsync(); // Update photos if (Request.Files.Count > 0) { var itemPictureQuery = _itemPictureService.Queryable().Where(x => x.ItemID == item.ID); if (itemPictureQuery.Count() > 0) nextPictureOrderId = itemPictureQuery.Max(x => x.Ordering); } foreach (HttpPostedFileBase file in files) { if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName)) { // Picture picture and get id var picture = new Picture(); picture.MimeType = "image/jpeg"; _pictureService.Insert(picture); await _unitOfWorkAsync.SaveChangesAsync(); // Format is automatically detected though can be changed. ISupportedImageFormat format = new JpegFormat { Quality = 90 }; Size size = new Size(500, 0); //https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/ // Initialize the ImageFactory using the overload to preserve EXIF metadata. using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true)) { var path = Path.Combine(Server.MapPath("~/images/item"), string.Format("{0}.{1}", picture.ID.ToString("00000000"), "jpg")); // Load, resize, set the format and quality and save an image. imageFactory.Load(file.InputStream) .Resize(size) .Format(format) .Save(path); } var itemPicture = new ItemPicture(); itemPicture.ItemID = item.ID; itemPicture.PictureID = picture.ID; itemPicture.Ordering = nextPictureOrderId; _itemPictureService.Insert(itemPicture); nextPictureOrderId++; } } await _unitOfWorkAsync.SaveChangesAsync(); // Update statistics count if (updateCount) { _sqlDbService.UpdateCategoryItemCount(item.CategoryID); _dataCacheService.RemoveCachedItem(CacheKeys.Statistics); } return RedirectToAction("Listings"); }
public async Task ResizeCache() { var fileName = Guid.NewGuid().ToString(); var width = (ushort)122; var format = new JpegFormat(); var id = Guid.NewGuid(); var versionName = Guid.NewGuid().ToString(); var cachedFileName = Guid.NewGuid().ToString(); var imaging = Substitute.For<IImaging>(); imaging.Get(Naming.DefaultExtension, 85).Returns(format); imaging.Resize(Arg.Any<byte[]>(), Arg.Any<ImageVersion>()); var container = Substitute.For<IContainer>(); var table = Substitute.For<ITableStorage>(); var queue = Substitute.For<IStorageQueue>(); var naming = Substitute.For<INaming>(); naming.FromFileName(fileName).Returns(id); naming.DynamicVersion(format.DefaultExtension, 85, width, 0).Returns(versionName); naming.FileName(id, versionName, format.DefaultExtension).Returns(cachedFileName); var store = new DataStore(imaging, container, table, queue, naming); var result = await store.Resize(fileName, width, 0, Naming.DefaultExtension, 85, true); Assert.IsNotNull(result); Assert.IsNotNull(result.Raw); Assert.AreEqual(format.MimeType, result.MimeType); naming.Received().FromFileName(fileName); naming.Received().DynamicVersion(format.DefaultExtension, 85, width, 0); naming.Received().FileName(id, versionName, format.DefaultExtension); imaging.Received().Get(Naming.DefaultExtension, 85); imaging.Received().Resize(Arg.Any<byte[]>(), Arg.Any<ImageVersion>()); }
public void ResizeImg(string file) { var replace = true; if (file == "") file = @"D:\img.jpeg"; var outfile = file; if (!replace) outfile = file.Replace(".jpeg", "_out" + DateTime.Now.ToString("MMddHHmmss") + ".jpeg"); var minDimMax = 256; byte[] photoBytes = File.ReadAllBytes(file); using (MemoryStream inStream = new MemoryStream(photoBytes)) { using (var img = System.Drawing.Image.FromStream(inStream)) { var w = img.Width; var h = img.Height; //if (w > minDimMax && h > minDimMax) //{ // Format is automatically detected though can be changed. ISupportedImageFormat format = new JpegFormat { Quality = 90 }; Size size1 = new Size(minDimMax, minDimMax * 10); Size size2 = new Size(minDimMax * 10, minDimMax); var resize1 = new ResizeLayer(size1, ResizeMode.Max); var resize2 = new ResizeLayer(size2, ResizeMode.Max); ResizeLayer layer = w < h ? resize1 : resize2; using (MemoryStream outStream = new MemoryStream()) { // Initialize the ImageFactory using the overload to preserve EXIF metadata. using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true)) { // Load, resize, set the format and quality and save an image. imageFactory.Load(inStream) .Resize(layer) .Format(format) .Save(outfile); } } //} //else if (!replace) //{ // File.Copy(file, outfile); //} } } }
public async Task<ActionResult> ListingUpdate(Listing listing, FormCollection form, IEnumerable<HttpPostedFileBase> files) { if (CacheHelper.Categories.Count == 0) { TempData[TempDataKeys.UserMessageAlertState] = "bg-danger"; TempData[TempDataKeys.UserMessage] = "[[[There are not categories available yet.]]]"; return RedirectToAction("Listing", new { id = listing.ID }); } var userIdCurrent = User.Identity.GetUserId(); // Register account if not login if (!User.Identity.IsAuthenticated) { var accountController = BeYourMarket.Core.ContainerManager.GetConfiguredContainer().Resolve<AccountController>(); var modelRegister = new RegisterViewModel() { Email = listing.ContactEmail, Password = form["Password"], ConfirmPassword = form["ConfirmPassword"], }; // Parse first and last name var names = listing.ContactName.Split(' '); if (names.Length == 1) { modelRegister.FirstName = names[0]; } else if (names.Length == 2) { modelRegister.FirstName = names[0]; modelRegister.LastName = names[1]; } else if (names.Length > 2) { modelRegister.FirstName = names[0]; modelRegister.LastName = listing.ContactName.Substring(listing.ContactName.IndexOf(" ") + 1); } // Register account var resultRegister = await accountController.RegisterAccount(modelRegister); // Add errors AddErrors(resultRegister); // Show errors if not succeed if (!resultRegister.Succeeded) { var model = new ListingUpdateModel() { ListingItem = listing }; // Populate model with listing await PopulateListingUpdateModel(listing, model); return View("ListingUpdate", model); } // update current user id var user = await UserManager.FindByNameAsync(listing.ContactEmail); userIdCurrent = user.Id; } bool updateCount = false; int nextPictureOrderId = 0; // Set default listing type ID if (listing.ListingTypeID == 0) { var listingTypes = CacheHelper.ListingTypes.Where(x => x.CategoryListingTypes.Any(y => y.CategoryID == listing.CategoryID)); if (listingTypes == null) { TempData[TempDataKeys.UserMessageAlertState] = "bg-danger"; TempData[TempDataKeys.UserMessage] = "[[[There are not listing types available yet.]]]"; return RedirectToAction("Listing", new { id = listing.ID }); } listing.ListingTypeID = listingTypes.FirstOrDefault().ID; } if (listing.ID == 0) { listing.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added; listing.IP = Request.GetVisitorIP(); listing.Expiration = DateTime.MaxValue.AddDays(-1); listing.UserID = userIdCurrent; listing.Enabled = true; listing.Currency = CacheHelper.Settings.Currency; updateCount = true; _listingService.Insert(listing); } else { if (await NotMeListing(listing.ID)) return new HttpUnauthorizedResult(); var listingExisting = await _listingService.FindAsync(listing.ID); listingExisting.Title = listing.Title; listingExisting.Description = listing.Description; listingExisting.Active = listing.Active; listingExisting.Price = listing.Price; listingExisting.ContactEmail = listing.ContactEmail; listingExisting.ContactName = listing.ContactName; listingExisting.ContactPhone = listing.ContactPhone; listingExisting.Latitude = listing.Latitude; listingExisting.Longitude = listing.Longitude; listingExisting.Location = listing.Location; listingExisting.ShowPhone = listing.ShowPhone; listingExisting.ShowEmail = listing.ShowEmail; listingExisting.CategoryID = listing.CategoryID; listingExisting.ListingTypeID = listing.ListingTypeID; listingExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified; _listingService.Update(listingExisting); } // Delete existing fields on item var customFieldItemQuery = await _customFieldListingService.Query(x => x.ListingID == listing.ID).SelectAsync(); var customFieldIds = customFieldItemQuery.Select(x => x.ID).ToList(); foreach (var customFieldId in customFieldIds) { await _customFieldListingService.DeleteAsync(customFieldId); } // Get custom fields var customFieldCategoryQuery = await _customFieldCategoryService.Query(x => x.CategoryID == listing.CategoryID).Include(x => x.MetaField.ListingMetas).SelectAsync(); var customFieldCategories = customFieldCategoryQuery.ToList(); foreach (var metaCategory in customFieldCategories) { var field = metaCategory.MetaField; var controlType = (BeYourMarket.Model.Enum.Enum_MetaFieldControlType)field.ControlTypeID; string controlId = string.Format("customfield_{0}_{1}_{2}", metaCategory.ID, metaCategory.CategoryID, metaCategory.FieldID); var formValue = form[controlId]; if (string.IsNullOrEmpty(formValue)) continue; formValue = formValue.ToString(); var itemMeta = new ListingMeta() { ListingID = listing.ID, Value = formValue, FieldID = field.ID, ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added }; _customFieldListingService.Insert(itemMeta); } await _unitOfWorkAsync.SaveChangesAsync(); if (Request.Files.Count > 0) { var itemPictureQuery = _listingPictureservice.Queryable().Where(x => x.ListingID == listing.ID); if (itemPictureQuery.Count() > 0) nextPictureOrderId = itemPictureQuery.Max(x => x.Ordering); } if (files != null && files.Count() > 0) { foreach (HttpPostedFileBase file in files) { if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName)) { // Picture picture and get id var picture = new Picture(); picture.MimeType = "image/jpeg"; _pictureService.Insert(picture); await _unitOfWorkAsync.SaveChangesAsync(); // Format is automatically detected though can be changed. ISupportedImageFormat format = new JpegFormat { Quality = 90 }; Size size = new Size(500, 0); //https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/ // Initialize the ImageFactory using the overload to preserve EXIF metadata. using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true)) { var path = Path.Combine(Server.MapPath("~/images/listing"), string.Format("{0}.{1}", picture.ID.ToString("00000000"), "jpg")); // Load, resize, set the format and quality and save an image. imageFactory.Load(file.InputStream) .Resize(size) .Format(format) .Save(path); } var itemPicture = new ListingPicture(); itemPicture.ListingID = listing.ID; itemPicture.PictureID = picture.ID; itemPicture.Ordering = nextPictureOrderId; _listingPictureservice.Insert(itemPicture); nextPictureOrderId++; } } } await _unitOfWorkAsync.SaveChangesAsync(); // Update statistics count if (updateCount) { _sqlDbService.UpdateCategoryItemCount(listing.CategoryID); _dataCacheService.RemoveCachedItem(CacheKeys.Statistics); } TempData[TempDataKeys.UserMessage] = "[[[Listing is updated!]]]"; return RedirectToAction("Listing", new { id = listing.ID }); }
public void GetJpeg() { var expected = new JpegFormat(); var i = new Imaging(); foreach (var extension in expected.FileExtensions) { var format = i.Get(extension); Assert.AreEqual(expected.GetType(), format.GetType()); } }
public static void TaskMain(string[] args) { if (args == null || args.Length != 4) { throw new Exception("Usage: ImageBlur.exe --Task <blobpath> <storageAccountName> <storageAccountKey>"); } string blobName = args[1]; string storageAccountName = args[2]; string storageAccountKey = args[3]; string workingDirectory = Environment.GetEnvironmentVariable("AZ_BATCH_TASK_WORKING_DIR"); int numberToBlur = 3; Console.WriteLine(); Console.WriteLine(" blobName: <{0}>", blobName); Console.WriteLine(" storageAccountName: <{0}>", storageAccountName); Console.WriteLine(" number to blur: <{0}>", numberToBlur); Console.WriteLine(); // get source image from cloud blob var storageCred = new StorageCredentials(storageAccountName, storageAccountKey); CloudBlockBlob blob = new CloudBlockBlob(new Uri(blobName), storageCred); using (MemoryStream inStream = new MemoryStream()) { blob.DownloadToStream(inStream); Image img = Image.FromStream(inStream); int imgWidth = img.Width; int imgHeight = img.Height; Size size = new Size(imgWidth, imgHeight); ISupportedImageFormat format = new JpegFormat { Quality = 70 }; // Print image properties to stdout Console.WriteLine(" Image Properties:"); Console.WriteLine(" Format: {0}", FormatUtilities.GetFormat(inStream)); Console.WriteLine(" Size: {0}", size.ToString()); Console.WriteLine(); for (var i = 0; i < numberToBlur; i++) { using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true)) { int blurIndex = (i * 5) + 10; imageFactory.Load(inStream); imageFactory.Resize(size) .Format(format) .GaussianBlur(blurIndex) .Save(workingDirectory + "/resultimage" + i + ".Jpeg"); //.Save(@"C:/Users/jiata/Desktop/imageblur/results/resultimage" + i + ".Jpeg"); } } } // TODO - not working for (var i = 0; i < numberToBlur; i++) { blob.UploadFromFile(workingDirectory + "/resultimage" + i + ".Jpeg", FileMode.Open); } Environment.Exit(1); }