void btnUpload_Click(object sender, EventArgs e) { //Loop through each uploaded file foreach (string fileKey in HttpContext.Current.Request.Files.Keys) { HttpPostedFile file = HttpContext.Current.Request.Files[fileKey]; if (file.ContentLength <= 0) continue; //Skip unused file controls. //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details. //Destination paths can have variables like <guid> and <ext> ImageJob i = new ImageJob(file, "~/uploads/<guid>_<filename:A-Za-z0-9>.<ext>", new ResizeSettings("width=200&height=200&format=jpg&crop=auto")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); } //Here's an example of getting a byte array for sending to SQL ////Loop through each uploaded file //foreach (string fileKey in HttpContext.Current.Request.Files.Keys) { // HttpPostedFile file = HttpContext.Current.Request.Files[fileKey]; // //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details. // ResizeSettings resizeCropSettings = new ResizeSettings("width=200&height=200&format=jpg&crop=auto"); // using (MemoryStream ms = new MemoryStream()) { // //Resize the image // ImageBuilder.Current.Build(file, ms, resizeCropSettings); // //Upload the byte array to SQL: ms.ToArray(); // } //} }
public Stream Resize(Stream image) { var memStream = new MemoryStream(); var i = new irp.ImageJob(image, memStream, new irp.Instructions("width=50;height=50;format=jpg;mode=max")); i.Build(); memStream.Position = 0; return(memStream); }
private static byte[] ProcessImage(byte[] image, Instructions instructions) { using (var outputImage = new MemoryStream()) { using (var inputImage = new MemoryStream(image)) { var job = new ImageJob(inputImage, outputImage, instructions); job.Build(); return outputImage.ToArray(); } } }
private bool CreateImageCrop(string imagePath, int imageWidth, int imageHeight, string savePath) { if (imageWidth < 0 || imageHeight < 0 || (imageWidth == 0 && imageHeight == 0)) { return(false); } ImageResizer.ImageJob i = new ImageResizer.ImageJob(imagePath, savePath, new ImageResizer.Instructions( "width=" + imageWidth + "&height=" + imageHeight + "&mode=crop&scache=disk&format=jpg")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); return(true); }
public void ProcessAndSaveImage(byte[] image, string pathWithName) { var imageBig = new ImageJob(image, pathWithName + "_normal", new Instructions("maxwidth=1500&maxheight=800&format=png")) { CreateParentDirectory = true, AddFileExtension = true }; imageBig.Build(); var imageSmall = new ImageJob(image, pathWithName + "_small", new Instructions("maxwidth=500&maxheight=300&format=png")) { CreateParentDirectory = true, AddFileExtension = true }; imageSmall.Build(); }
public Photo(HttpPostedFileBase file, NameValueCollection defaultQuery =null, NameValueCollection preprocessingQuery = null) { Id = Guid.NewGuid(); OriginalName = file.FileName; string newPath = PathUtils.SetExtension(Id.ToString(),PathUtils.GetExtension(OriginalName)); FilePath = newPath; if (!Directory.Exists(StoragePath))Directory.CreateDirectory(StoragePath); if (preprocessingQuery == null || !Config.Current.Pipeline.IsAcceptedImageType(OriginalName)) { file.SaveAs(Path.Combine(StoragePath, newPath)); } else { var j = new ImageJob(file, Path.Combine(StoragePath, Id.ToString()), new ResizeSettings(preprocessingQuery)); j.AddFileExtension = true; j.Build(); FilePath = Path.GetFileName(j.FinalPath); } Query = defaultQuery != null ? defaultQuery : new NameValueCollection(); }
public static void Upload(FileUpload fileUpload) { Repository repo = new Repository(); const string uploadPath = "upload"; if (fileUpload == null) { return; } foreach (HttpPostedFile postedFile in fileUpload.PostedFiles) { string fileName = postedFile.FileName; ImageResizer.ImageJob originalImage = new ImageResizer.ImageJob(postedFile, "~/" + uploadPath + "/" + fileName, new ImageResizer.Instructions("quality=72; mode=max")); originalImage.CreateParentDirectory = true; originalImage.Build(); Image dbImage = new Image(); dbImage.Filename = fileName; repo.CreateImage(dbImage); } }
public MemoryStream GenerateThumbnail(string videoId, int size) { try { var url = "http://vimeo.com/api/oembed.json?url=http%3A//vimeo.com/" + videoId; var request = WebRequest.Create(url); string text; var response = (HttpWebResponse)request.GetResponse(); using (var sr = new StreamReader(response.GetResponseStream())) { text = sr.ReadToEnd(); } dynamic job = JObject.Parse(text); var webClient = new WebClient(); byte[] imageBytes = webClient.DownloadData(job.thumbnail_url.ToString()); //var source = ResizeStream(imageBytes, 300); var ms = new MemoryStream(imageBytes); var dest = new MemoryStream(); var r = new ResizeSettings() { }; r.MaxWidth = size; r.Format = "jpg"; var eee = new ImageResizer.ImageJob(ms, dest, r); eee.Build(); return(dest); } catch (Exception) { return(null); } }
protected void chatRoomImgUpload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e) { if (!SAVECLICKED) { try { string savePath = Helper.GetUniqueNameUser(e.FileName, MapPath("~/Images/user/")); if (savePath != null) { //chatRoomImgUpload.SaveAs(savePath); //string newName = "I_" + Path.GetFileName(savePath); //Helper.ResizeImageFile(savePath, 50, Path.Combine(MapPath("~/Images/chatroom/"), newName)); /********************************************************/ HttpPostedFile file = chatRoomImgUpload.PostedFile; ImageResizer.ImageJob i = new ImageResizer.ImageJob(file, savePath, new ImageResizer.ResizeSettings("width=50;height=50;format=jpg;mode=pad")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); /********************************************************/ string virtPath = "~/Images/user/" + Path.GetFileName(savePath); string finalPath = System.Web.VirtualPathUtility.ToAbsolute(virtPath); Session.Add(USER_SAVE_STRING, virtPath); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size" + new Guid(), "top.$get(\"" + imgUser.ClientID + "\").setAttribute(\"src\", \"" + Server.HtmlEncode(finalPath) + "\");", true); } else { } } catch (Exception ex) { //Console.WriteLine(ex.StackTrace); } } else { SAVECLICKED = false; } }
public void UploadFilesToStorageAccount(HttpPostedFileBase file, string newFileName, string resizeSettings) { // CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudStorageAccount storageAccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(SiteSettings.AzureAccountName, SiteSettings.AzureStorageKey), false); var storageClient = storageAccount.CreateCloudBlobClient(); var storageContainer = storageClient.GetContainerReference(ConfigurationManager.AppSettings.Get("CloudStorageContainerReference")); storageContainer.CreateIfNotExists(); // Retrieve reference to the blob we want to create CloudBlockBlob blockBlob = storageContainer.GetBlockBlobReference(newFileName + ".jpg"); // Populate our blob with contents from the uploaded file. using (var ms = new MemoryStream()) { ImageResizer.ImageJob ij = new ImageResizer.ImageJob(file.InputStream, ms, new ImageResizer.ResizeSettings(resizeSettings), false, false); ij.ResetSourceStream = true; ij.Build(); blockBlob.Properties.ContentType = "image/jpeg"; ms.Seek(0, SeekOrigin.Begin); blockBlob.UploadFromStream(ms); } }
internal static List<string> UploadImage(HttpPostedFileBase upload, bool isProfile) { var basePath = HostingEnvironment.ApplicationPhysicalPath; var path = new List<string>(); var commonResizeSettings = new ResizeSettings("width=800;height=800;format=jpg;mode=max"); var thumbsResizeSettings = new ResizeSettings("width=200;height=200;format=jpg;mode=max"); if (isProfile) { commonResizeSettings = new ResizeSettings("width=400;height=400;format=jpg;mode=max"); } using (Stream newFile = System.IO.File.Create(basePath + "\\temp\\temp.jpg")) { ImageJob i = new ImageJob(); i.ResetSourceStream = true; i = new ImageJob(upload.InputStream, newFile, commonResizeSettings); i.CreateParentDirectory = false; //Auto-create the uploads directory. i.Build(); } using (FileStream file = new FileStream(basePath + "\\temp\\temp.jpg", FileMode.Open)) { path.Add(Dropbox.Upload(upload.FileName, file)); } ImageBuilder.Current.Build(basePath + "\\temp\\temp.jpg", basePath + "\\temp\\temp.jpg", thumbsResizeSettings); using (FileStream file = new FileStream(basePath + "\\temp\\temp.jpg", FileMode.Open)) { path.Add(Dropbox.Upload(upload.FileName, file, "Thumbnails")); } return path; }
public Response GetHotelImage(dynamic parameters) { var hotelId = parameters.hotelid; var imageWidth = parameters.width; var imageHeight = parameters.height; var response = new Response(); var hotel = this.TravelOffersRepository.GetHotel(hotelId); if (hotel == null || string.IsNullOrEmpty(hotel.ImageUrl)) { response.StatusCode = HttpStatusCode.NotFound; return response; } var imageResponse = this.ImageDownloadClient.GetAsync(hotel.ImageUrl).Result; if (!imageResponse.IsSuccessStatusCode) { response.StatusCode = (HttpStatusCode)imageResponse.StatusCode; return response; } var resizeSettings = string.Format("width={0}&height={1}&crop=auto", imageWidth, imageHeight); response.ContentType = imageResponse.Content.Headers.ContentType.MediaType; response.Contents = stream => { var imageStream = imageResponse.Content.ReadAsStreamAsync().Result; var i = new ImageJob(imageStream, stream, new ResizeSettings(resizeSettings)); i.Build(); }; return response; }
public int ResizeImage(FileAndCustomResizeSetting image) { int result; try { ImageJob i = new ImageJob(image.FileSource, image.NewFileName, image.CustomResizeSetting, false, false); i.CreateParentDirectory = true;//Auto-create the uploads directory. i.Build(); StatusOfImage localStatus; ListOfFileAndCustomResizeSettings.TryGetValue(image, out localStatus); localStatus.Status = 3; localStatus.FinishTime = DateTime.Now; result = localStatus.Status; } catch { StatusOfImage localStatus; ListOfFileAndCustomResizeSettings.TryGetValue(image, out localStatus); localStatus.Status = 0; result = 0; } return result; }
protected void Upload_Image() { foreach (string fileKey in HttpContext.Current.Request.Files.Keys) { HttpPostedFile file = HttpContext.Current.Request.Files[fileKey]; if (file.ContentLength <= 0) { continue; } string fileExtension = file.FileName.Substring(file.FileName.LastIndexOf('.') + 1); var job = new ImageJob( file, "~/Images/" + this.UserName.Text + "/avatar." + fileExtension, new Instructions("width=250;height=250;format=" + fileExtension + ";mode=max;")); job.CreateParentDirectory = true; job.Build(); } }
private void Resize(String image, string location, string fileName, int height = 104, int width = 104, string original = null) { var srcImage = Image.FromFile(image); var imageJob = new ImageJob(srcImage, string.Format("{0}{1}", location, fileName), new ResizeSettings(width, height, FitMode.Max, null)); try { imageJob.Build(); srcImage.Dispose(); if (!string.IsNullOrEmpty(original)) System.IO.File.Delete(original); } catch (Exception ex) { throw ex; } }
private void ExecuteImageJob(object dest, bool appendCorrectExtension, Stream inputStream, string path) { ImageJob j = new ImageJob(); j.Source = inputStream != null ? (object)inputStream : path; j.Dest = dest; j.AddFileExtension = appendCorrectExtension; j.Settings = new ResizeSettings(CroppedUrlQuerystring); Logger.Trace("ImageJob.Settings = {0}", j.Settings); // NameValueCollection data = CroppedUrlQuerystring; // j.Settings["cropxunits"] = data["cropxunits"]; // j.Settings["cropyunits"] = data["cropyunits"]; // j.Settings.Quality = this.JpegQuality; // if (!string.IsNullOrEmpty(this.ForcedImageFormat)) // j.Settings.Format = this.ForcedImageFormat; // j.Settings["crop"] = "(" + X + ", " + Y + ", " + (X + W) + ", " + (Y + H) + ")"; j.Build(); }
private bool CreateImage(string imagePath, int imageWidth, int imageHeight, string savePath) { //Trường hợp 1 trong 2 giá trị âm hoặc cùng = 0 thì ko tạo ảnh thumb if (imageWidth < 0 || imageHeight < 0 || (imageWidth == 0 && imageHeight == 0)) { return(false); } //Duong dan thuc cua file goc //imagePath = HttpContext.Current.Server.MapPath(imagePath); //Duong dan thuc cua file thumbnail //savePath = HttpContext.Current.Server.MapPath(savePath); //Tao file thumbnail //ImageBuilder.Current.Build(imagePath, savePath, new ResizeSettings("width=" + imageWidth + "&height=" + imageHeight + "&mode=max&format=jpg"), false, true); ImageResizer.ImageJob i = new ImageResizer.ImageJob(imagePath, savePath, new ImageResizer.Instructions( "width=" + imageWidth + "&height=" + imageHeight + "&mode=max&format=jpg")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); return(true); //// Read the source image //var photo = File.ReadAllBytes(imagePath); //var factory = (IWICComponentFactory)new WICImagingFactory(); //var inputStream = factory.CreateStream(); //inputStream.InitializeFromMemory(photo, (uint)photo.Length); //var decoder = factory.CreateDecoderFromStream(inputStream, null, WICDecodeOptions.WICDecodeMetadataCacheOnLoad); //var frame = decoder.GetFrame(0); //// Compute target size //uint width, height, thumbWidth, thumbHeight; //frame.GetSize(out width, out height); ////if (width > height) ////{ //// thumbWidth = (uint)imageWidth; //// thumbHeight = (uint)(height * imageHeight / imageWidth); ////} ////else ////{ //// thumbWidth = (uint)(width * imageWidth / height); //// thumbHeight = (uint)imageHeight; ////} //if (imageHeight == 0 || imageHeight * width > imageWidth * height) //{ // thumbHeight = (uint)((imageWidth * height) / width); // thumbWidth = (uint)imageWidth; //} //else //{ // thumbWidth = (uint)((imageHeight * width) / height); // thumbHeight = (uint)imageHeight; //} //using (MemoryIStream outputStream = new MemoryIStream()) //{ // // Prepare JPG encoder // var encoder = factory.CreateEncoder(Consts.GUID_ContainerFormatJpeg, null); // encoder.Initialize(outputStream, WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache); // // Prepare output frame // IWICBitmapFrameEncode outputFrame; // var arg = new IPropertyBag2[1]; // encoder.CreateNewFrame(out outputFrame, arg); // var propBag = arg[0]; // var propertyBagOption = new PROPBAG2[1]; // propertyBagOption[0].pstrName = "ImageQuality"; // propBag.Write(1, propertyBagOption, new object[] { 0.85F }); // outputFrame.Initialize(propBag); // outputFrame.SetResolution(96, 96); // outputFrame.SetSize(thumbWidth, thumbHeight); // // Prepare scaler // var scaler = factory.CreateBitmapScaler(); // scaler.Initialize(frame, thumbWidth, thumbHeight, WICBitmapInterpolationMode.WICBitmapInterpolationModeFant); // // Write the scaled source to the output frame // outputFrame.WriteSource(scaler, new WICRect { X = 0, Y = 0, Width = (int)thumbWidth, Height = (int)thumbHeight }); // outputFrame.Commit(); // encoder.Commit(); // var outputArray = outputStream.ToArray(); // // Write to the cache file // File.WriteAllBytes(savePath, outputArray); //} }
/// <summary> /// Creates the favicon. /// </summary> /// <param name="rootFolder">The root folder.</param> /// <param name="originalFile">The original file.</param> /// <param name="filePrefix">The file prefix.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> public override void CreateFavicon( ContentReference rootFolder, Stream originalFile, string filePrefix, int width, int height) { //Get a suitable MediaData type from extension Type mediaType = this.ContentMediaResolver.Service.GetFirstMatching(".png"); ContentType contentType = this.ContentTypeRepository.Service.Load(mediaType); try { //Get a new empty file data ImageData media = this.ContentRepository.Service.GetDefault<ImageData>(rootFolder, contentType.ID); media.Name = string.Format(CultureInfo.InvariantCulture, "{0}-{1}x{2}.png", filePrefix, width, height); //Create a blob in the binary container Blob blob = this.BlobFactory.Service.CreateBlob(media.BinaryDataContainer, ".png"); ImageJob imageJob = new ImageJob( originalFile, blob.OpenWrite(), new Instructions( string.Format( CultureInfo.InvariantCulture, "width={0}&height={1}&crop=auto&format=png", width, height))) { ResetSourceStream = true, DisposeDestinationStream = true, DisposeSourceObject = false }; imageJob.Build(); //Assign to file and publish changes media.BinaryData = blob; this.ContentRepository.Service.Save(media, SaveAction.Publish); } catch (AccessDeniedException accessDeniedException) { Logger.Error("[Favicons] Error creating icon.", accessDeniedException); } catch (ArgumentNullException argumentNullException) { Logger.Error("[Favicons] Error creating icon.", argumentNullException); } catch (FormatException formatException) { Logger.Error("[Favicons] Error creating icon.", formatException); } }
public Stream Resize( Stream sourceStream, int? width = null, int? height = null) { using (var cloned = new MemoryStream()) { sourceStream.Seek(0, SeekOrigin.Begin); sourceStream.CopyTo(cloned); cloned.Seek(0, SeekOrigin.Begin); var memory = new MemoryStream(); var imgJob = new ImageJob(cloned, memory, new Instructions()); if (width.HasValue && height.HasValue) { imgJob.Instructions = new Instructions( new NameValueCollection { {"width", width.Value.ToString()}, {"height", height.Value.ToString()}, {"format", "jpg"}, {"mode", "crop"} }); imgJob.Build(); return memory; } if (width.HasValue) { imgJob.Instructions = new Instructions( new NameValueCollection { {"width", width.Value.ToString()}, {"format", "jpg"}, {"mode", "crop"} }); imgJob.Build(); return memory; } if (height.HasValue) { imgJob.Instructions = new Instructions( new NameValueCollection { {"height", height.Value.ToString()}, {"format", "jpg"}, {"mode", "crop"} }); imgJob.Build(); return memory; } imgJob.Instructions = new Instructions( new NameValueCollection { {"format", "jpg"}, {"mode", "crop"} }); imgJob.Build(); return memory; } }
public ActionResult ImagesUpload(HttpPostedFileBase[] files, string sessionKey, int? defaultImageIndex) { ProductSessionObject sObject = (ProductSessionObject)Session[sessionKey]; string thumbsPath = ProductImage.DefaultThumbDirectory, imagesPath = ProductImage.DefaultImageDirectory; //If images were uploaded and there were no default image selected, //then the first one is our default. if (files.Count() > 0 && !defaultImageIndex.HasValue) { defaultImageIndex = 0; } //Defines the image resizing and format settings for thumbnails Instructions thumbResizeSettings = new Instructions() { Width = 300, Height = 400, Mode = FitMode.Pad }; foreach (var item in files) { string extension = Path.GetExtension(item.FileName).ToLower(); if (extension == ".png" || extension == ".jpg" || extension == ".jpeg") { ProductImage image = new ProductImage(); //First we resize/save the thmbnail. //ImageResizer can generate the filename using variables like these <guid> and <ext> below. //I guess their working is obvious, so I won't explain. ImageResizer.ImageJob thumbImageJob = new ImageResizer.ImageJob(item, string.Format("{0}<guid>.<ext>", thumbsPath), thumbResizeSettings); thumbImageJob.Build(); //Setting the filename for the full image and for its thumbnail image.Filename = Path.GetFileName(thumbImageJob.FinalPath); image.ThumbFilename = image.Filename; //Finally, save the full image with the same name as the thumbnail item.SaveAs(Server.MapPath(imagesPath + image.Filename)); //Adds the newly uploaded image object do the Session Object. NOT to database. sObject.Images.Add(image); } } ViewBag.defaultImageIndex = defaultImageIndex; return PartialView(sObject.Images); }
public static string SaveUploadImage(HttpPostedFileBase pHttpPostedFileBase, string pFilePhysicalFolderPath, bool pIsCropImage = false, bool IsGenerateVersion = true, Dictionary<string, string> pUploadImageVersions = null, string pOldFileName = "", string newFileName = "") { if (!string.IsNullOrEmpty(pHttpPostedFileBase.FileName)) { string fileName = string.IsNullOrEmpty(newFileName) ? DateTime.Now.Ticks.ToString() + Path.GetExtension(pHttpPostedFileBase.FileName) : newFileName; string filePhysicalFolderPath = pFilePhysicalFolderPath; string filePath = Path.Combine(filePhysicalFolderPath, fileName); CommonLogic.CreateDirectory(filePhysicalFolderPath); if (pIsCropImage) { #region CROP IMAGE int x1 = Convert.ToInt32(Math.Round(CommonLogic.CDec(HttpContext.Current.Request.Form["jcrop-x1"]))); int y1 = Convert.ToInt32(Math.Round(CommonLogic.CDec(HttpContext.Current.Request.Form["jcrop-y1"]))); int x2 = Convert.ToInt32(Math.Round(CommonLogic.CDec(HttpContext.Current.Request.Form["jcrop-x2"]))); int y2 = Convert.ToInt32(Math.Round(CommonLogic.CDec(HttpContext.Current.Request.Form["jcrop-y2"]))); int w = Convert.ToInt32(Math.Round(CommonLogic.CDec(HttpContext.Current.Request.Form["jcrop-w"]))); int h = Convert.ToInt32(Math.Round(CommonLogic.CDec(HttpContext.Current.Request.Form["jcrop-h"]))); if (x1 >= 0 && y1 >= 0 && x2 > 0 && y2 > 0) { string cropCollection = string.Format("crop={0},{1},{2},{3};", x1, y1, x2, y2); ImageJob cropImage = new ImageJob(pHttpPostedFileBase.InputStream, filePath, new ResizeSettings(cropCollection)); cropImage.Build(); } else { pHttpPostedFileBase.SaveAs(filePath); } #endregion } else { pHttpPostedFileBase.SaveAs(filePath); } #region GENERATE IMAGE VERSION if (IsGenerateVersion) { if (pUploadImageVersions != null) { Dictionary<string, string> imageVersions = pUploadImageVersions; //Generate each version foreach (string prefix in imageVersions.Keys) { string resizeFileName = Path.Combine(filePhysicalFolderPath, prefix + fileName); resizeFileName = ImageBuilder.Current.Build(filePath, resizeFileName, new ResizeSettings(imageVersions[prefix]), false, false); } } } #endregion #region DELETE OLD FILE if (!string.IsNullOrEmpty(pOldFileName)) { DeleteUploadImageFile(pFilePhysicalFolderPath, pOldFileName); } #endregion return fileName; } return string.Empty; }
public static void copyOriginalImageToRespectives(ImageType type, string filename, ResizeSettings rs,bool disposeSource, bool addFileExtensions) { string StrRootPath = HostingEnvironment.MapPath("~/"); string SourceFolder = StrRootPath + @"Modules\AspxCommerce\AspxItemsManagement\uploads\" + @"" + filename + ""; string DestinationFolder = StrRootPath + @"Modules\AspxCommerce\AspxItemsManagement\uploads\" + @"" + type + @"\" + filename + ""; using (FileStream fileStream = new FileStream(SourceFolder, FileMode.Open)) { ImageJob i = new ImageJob(fileStream, DestinationFolder,new Instructions(rs)); i.CreateParentDirectory = false; //Auto-create the uploads directory. i.Build(); } }
private static void MakeLightbox(string filePath, string fileName) { var thumbPath = Path.Combine(Path.Combine(Path.GetDirectoryName(filePath), "lightbox"), fileName); try { var job = new ImageJob(filePath, thumbPath, lightboxResizeSettings); job.CreateParentDirectory = true; job.Build(); } catch (Exception e) { Trace.TraceInformation(e.ToString()); } }
/// <summary> /// Copies image file to the destination.The destination need not have the file but the destination must add the original file name in its path /// </summary> /// <param name="rs">The resize setting</param> /// <param name="SourceFile">The original image file</param> /// <param name="DestinationFolder">The path of the destination folder including the filename same as original image file</param> public static void copyOriginalImageToRespectives(ResizeSettings rs, string SourceFile, string DestinationFolder,AspxCommonInfo aspxCommonObj,IsWaterMark isWaterMark) { // string combinedPath = Path.Combine(SourceFolder, filename); if (isWaterMark.ToString() == "True") { //ResizeSettings settingObj = ApplyWaterMarkToImage(aspxCommonObj, rs,SourceFile, DestinationFolder); } else { using (FileStream fileStream = new FileStream(SourceFile, FileMode.Open)) { ImageJob i = new ImageJob(fileStream, DestinationFolder, new Instructions(rs)); i.CreateParentDirectory = false; //Auto-create the uploads directory. i.Build(); } } }
public async Task<HttpResponseMessage> PostFile(string key) { string user_id = User.Identity.Name; handle logged_in = (from handle r in db.handles where r.userGuid.Equals(User.Identity.Name) select r).FirstOrDefault(); thread referring_thread = (from thread r in db.threads where r.groupKey == key select r).FirstOrDefault(); // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string orig_dir = HttpContext.Current.Server.MapPath("~/snaps/orig/"); string sz500_dir = HttpContext.Current.Server.MapPath("~/snaps/500/"); string sz640_dir = HttpContext.Current.Server.MapPath("~/snaps/640/"); string thumb_dir = HttpContext.Current.Server.MapPath("~/snaps/thumb/"); var provider = new MultipartFormDataStreamProvider(orig_dir); try { StringBuilder sb = new StringBuilder(); // Holds the response body // Read the form data and return an async task. await Request.Content.ReadAsMultipartAsync(provider); // This illustrates how to get the form data. foreach (var item_key in provider.FormData.AllKeys) { foreach (var val in provider.FormData.GetValues(item_key)) { sb.Append(string.Format("{0}: {1}\n", item_key, val)); } } selfy self = new selfy(); // This illustrates how to get the file names for uploaded files. foreach (var file in provider.FileData) { FileInfo fileInfo = new FileInfo(file.LocalFileName); sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length)); thread group_key = (from m in db.threads where m.groupKey.StartsWith(key) select m).FirstOrDefault(); self.dateCreated = DateTime.UtcNow; self.selfieGuid = group_key.groupKey; self.userGuid = "1"; db.selfies.Add(self); db.SaveChanges(); referring_thread.uploadSuccess = 1; // update the thread so it knows that // an image has been successfully uploaded to it db.threads.Attach(referring_thread); var updated_thread = db.Entry(referring_thread); updated_thread.Property(e => e.uploadSuccess).IsModified = true; db.SaveChanges(); string copied_orig_to_path = orig_dir + self.selfieGuid; if (Directory.Exists(orig_dir) == false) { Directory.CreateDirectory(orig_dir); } fileInfo.CopyTo(copied_orig_to_path); // generate 500px version string fileName = sz500_dir + self.selfieGuid; ImageResizer.ImageJob i = new ImageResizer.ImageJob(copied_orig_to_path, fileName, new ImageResizer.Instructions( "width=500;height=900;format=jpg;mode=max;autorotate=true")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); // generate 640px version (retina display) fileName = sz640_dir + self.selfieGuid; i = new ImageResizer.ImageJob(copied_orig_to_path, fileName, new ImageResizer.Instructions( "width=640;height=900;format=jpg;mode=max;autorotate=true")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); // generate thumb version fileName = thumb_dir + self.selfieGuid; i = new ImageResizer.ImageJob(copied_orig_to_path, fileName, new ImageResizer.Instructions( "width=75;height=75;format=jpg;mode=max;autorotate=true")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); fileInfo.Delete(); } var response = new HttpResponseMessage() { Content = new StringContent(self.selfieGuid.ToString()) }; return response; } catch (System.Exception e) { string result = e.Message.ToString(); if (e.InnerException != null) { result = result + " - " + e.InnerException.Message.ToString(); } var response = new HttpResponseMessage() { Content = new StringContent(e.Message.ToString()) }; return response; } }
/// <summary> /// Crops the original image and saves it to the specified path. /// </summary> /// <param name="destPath"></param> /// <param name="appendCorrectExtension">If true, the appropriate image extension will be added</param> public void Crop(string destPath, bool appendCorrectExtension) { string path = ImagePath != null ? ImagePath : CroppedUrl; //Fix relative paths if (!path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !path.StartsWith("~") && !path.StartsWith("/")) { path = ResolveUrl(path); //No relative paths here. } //Fix domain-relative paths into app-relative paths if they're in the same application. if (path.StartsWith("/") && path.StartsWith(HostingEnvironment.ApplicationVirtualPath, StringComparison.OrdinalIgnoreCase)) { path = "~/" + path.Substring(HostingEnvironment.ApplicationVirtualPath.Length).TrimStart('/'); } Stream s = null; try { //Handle same-domain, external apps if (path.StartsWith("/")) { s = GetUriStream(new Uri(new Uri(Page.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped)), new Uri(path))); } else if (!path.StartsWith("~")) { //Everything else s = GetUriStream(new Uri(path)); } ImageJob j = new ImageJob(); j.Source = s != null ? (object)s : path; j.Dest = destPath; j.AddFileExtension = appendCorrectExtension; j.Settings = new ResizeSettings(CroppedUrlQuerystring); NameValueCollection data = CroppedUrlQuerystring; j.Settings["cropxunits"] = data["cropxunits"]; j.Settings["cropyunits"] = data["cropyunits"]; j.Settings.Quality = this.JpegQuality; if (!string.IsNullOrEmpty(this.ForcedImageFormat)) j.Settings.Format = this.ForcedImageFormat; j.Settings["crop"] = "(" + X + ", " + Y + ", " + (X + W) + ", " + (Y + H) + ")"; j.Build(); } finally { if (s != null) s.Dispose(); } }
private void SaveProfileImageToServer() { foreach (string fileKey in this.Context.Request.Files.Keys) { HttpPostedFile file = HttpContext.Current.Request.Files[fileKey]; if (file.ContentLength <= 0) { continue; } string fileExtension = file.FileName.Substring(file.FileName.LastIndexOf('.') + 1); string userEmail = this.Server.HtmlEncode(this.Email.Text); var job = new ImageJob( file, "~/Images/" + userEmail + "/avatar." + fileExtension, new Instructions("width=250;height=250;format=" + fileExtension + ";mode=max;")); job.CreateParentDirectory = true; job.Build(); } }
private static MemoryStream ResizeImage(Stream inputStream, double width) { var memoryStream = new MemoryStream(); var i = new ImageJob(inputStream, memoryStream, new Instructions($"width={width}")); i.Build(); return memoryStream; }
private static MemoryStream ResizeImage(byte[] downloaded, int width, int height) { var inputStream = new MemoryStream(downloaded); var memoryStream = new MemoryStream(); var settings = string.Format("width={0}&height={1}", width, height); var i = new ImageJob(inputStream, memoryStream, new ResizeSettings(settings)); i.Build(); return memoryStream; }
protected void btnUploadAndGenerate_Click(object sender, EventArgs e) { Dictionary<string, string> versions = new Dictionary<string, string>(); //Define the version to generate versions.Add("_thumb", "width=100&height=100&crop=auto&format=jpg"); //Crop to square thumbnail versions.Add("_medium", "maxwidth=400&maxheight=400format=jpg"); //Fit inside 400x400 area, jpeg versions.Add("_large", "maxwidth=1900&maxheight=1900&format=jpg"); //Fit inside 1900x1200 area //Loop through each uploaded file foreach (string fileKey in HttpContext.Current.Request.Files.Keys) { HttpPostedFile file = HttpContext.Current.Request.Files[fileKey]; if (file.ContentLength <= 0) continue; //Skip unused file controls. //Generate each version foreach (string suffix in versions.Keys) { ImageJob i = new ImageJob(file, "~/uploads/<guid>" + suffix + ".<ext>", new ResizeSettings(versions[suffix])); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); } } }