public void Resize(string source, string destination, int height) { try { using (var sourceStream = _diskProvider.OpenReadStream(source)) { using (var outputStream = _diskProvider.OpenWriteStream(destination)) { var settings = new Instructions(); settings.Height = height; var job = new ImageJob(sourceStream, outputStream, settings); ImageBuilder.Current.Build(job); } } } catch { if (_diskProvider.FileExists(destination)) { _diskProvider.DeleteFile(destination); } throw; } }
public static void GenerateVersions(string original) { Dictionary<string, string> versions = new Dictionary<string, string>(); //Define the versions to generate and their filename suffixes. versions.Add("_thumb", "width=300&height=300&crop=auto&format=jpg"); versions.Add("_large", "maxwidth=1024&maxheight=768&format=jpg&mode=max"); string basePath = PathUtils.RemoveExtension(original); //Generate each version foreach (string suffix in versions.Keys) { var job = new ImageJob { Source = original, Dest = basePath + suffix, Instructions = new Instructions(versions[suffix]), DisposeSourceObject = false, AddFileExtension = true, CreateParentDirectory = true }; ImageBuilder.Current.Build(job); //Let the image builder add the correct extension based on the output file type //ImageBuilder.Current.Build(original, basePath + suffix, // new ResizeSettings(versions[suffix]), false, true); } }
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 static void GenerateVersions(Stream source, string baseFileName) { Dictionary<string, string> versions = new Dictionary<string, string>(); //Define the versions to generate and their filename suffixes. versions.Add("_thumb", "width=300&height=300&crop=auto&format=jpg"); versions.Add("_large", "maxwidth=1024&maxheight=768&format=jpg&mode=max"); // Ensure that no extensions are in the file name. string basePath = PathUtils.RemoveExtension(baseFileName); using (source) { //Generate each version foreach (string suffix in versions.Keys) { var job = new ImageJob { Source = source, Dest = basePath + suffix, Instructions = new Instructions(versions[suffix]), DisposeSourceObject = false, AddFileExtension = true, ResetSourceStream = true, CreateParentDirectory = true }; ImageBuilder.Current.Build(job); } } }
/// <summary> /// Returns the [width,height] of the first frame/page of the image. May return null or throw exceptions. /// </summary> /// <param name="s">May be an UploadFile, a seekable Stream, a physical path, or a virtual path to the image.</param> /// <returns></returns> public int[] GetImageSize(object s) { var j = new ImageJob(s,null); j.ResetSourceStream = true; j.DisposeSourceObject = false; c.CurrentImageBuilder.Build(j); return new int[]{j.SourceWidth.Value,j.SourceHeight.Value}; }
private void CropImage(Rectangle cp, Stream source, MemoryStream croppedImage) { var imageResizer = new ImageResizer.Configuration.Config(); string cropFormat = $"?crop={cp.Left},{cp.Top},{cp.Right},{cp.Bottom}"; var resizeJob = new ImageResizer.ImageJob(source, croppedImage, new Instructions(cropFormat)); imageResizer.Build(resizeJob); }
/// <summary> /// Returns the [width,height] of the first frame/page of the image. May return null or throw exceptions. /// </summary> /// <param name="s">May be an UploadFile, a seekable Stream, a physical path, or a virtual path to the image.</param> /// <returns></returns> public int[] GetImageSize(object s) { var j = new ImageJob(s, null); j.ResetSourceStream = true; j.DisposeSourceObject = false; c.CurrentImageBuilder.Build(j); return(new int[] { j.SourceWidth.Value, j.SourceHeight.Value }); }
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); } }
public static void SaveImage(Stream source, int width, int height, string path, FitMode mode, bool dispose = true, bool resetSource = false) { var instructions = new Instructions { Width = width, Height = height, Mode = mode, Encoder = "freeimage", OutputFormat = OutputFormat.Jpeg }; var job = new ImageJob { Instructions = instructions, Source = source, Dest = path, CreateParentDirectory = true, ResetSourceStream = resetSource, DisposeSourceObject = dispose, AddFileExtension = !Path.HasExtension(path) }; ImageBuilder.Current.Build(job); }
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; }
/// <summary> /// Build file info object based on existing info & processing result. The result represents stored file but not the original one. /// For example if the original was a jpeg image, but after processing it's converted into png, file ext & mime type will be updated. /// </summary> /// <param name="fileInfo">Income file info</param> /// <param name="job">Processing result</param> /// <returns></returns> protected virtual IFileInfo BuildFileInfo(IFileInfo fileInfo, ImageJob job) { var fileExt = job.ResultFileExtension; var mediaType = job.ResultMimeType ?? fileInfo.MimeType; var res = new IncomeFileInfo(fileInfo) { MimeType = mediaType }; if (fileExt != null && !res.OriginalName.EndsWith(fileExt, StringComparison.OrdinalIgnoreCase)) { // Need to correct file ext var dotIndex = res.OriginalName.LastIndexOf('.'); if (dotIndex > 0) { res.OriginalName = res.OriginalName.Substring(0, dotIndex); } res.OriginalName += '.' + fileExt; } var extra = new Dictionary<string, string>(); if (job.FinalHeight.HasValue) extra.Add("Height", job.FinalHeight.Value.ToString("D")); if (job.FinalWidth.HasValue) extra.Add("Width", job.FinalWidth.Value.ToString("D")); if (job.Dest is Stream) extra.Add("Size", ((Stream)job.Dest).Length.ToString("D")); if (extra.Count > 0) res.Extra = extra; return res; }
/// <summary> /// Generates the resized image to disk (if needed), then rewrites the request to that location. /// Perform 404 checking before calling this method. Assumes file exists. /// Called during PostAuthorizeRequest /// </summary> /// <param name="context"></param> /// <param name="ra"></param> /// <param name="vf"></param> protected virtual void HandleRequest(HttpContext context, HttpModuleRequestAssistant ra, IVirtualFile vf) { if (!ra.CachingIndicated && !ra.ProcessingIndicated) { ra.ApplyRewrittenPath(); //This is needed for both physical and virtual files; only makes changes if needed. if (vf != null) { ra.AssignSFH(); //Virtual files are not served in .NET 4. } return; } context.Items[conf.ResponseArgsKey] = ""; //We are handling the request //Communicate to the MVC plugin this request should not be affected by the UrlRoutingModule. context.Items[conf.StopRoutingKey] = true; ra.EstimateResponseInfo(); //Build CacheEventArgs ResponseArgs e = new ResponseArgs(); //Add the modified date to the request key, if present. var modDate = (vf == null) ? System.IO.File.GetLastWriteTimeUtc(ra.RewrittenMappedPath) : (vf is IVirtualFileWithModifiedDate ? ((IVirtualFileWithModifiedDate)vf).ModifiedDateUTC : DateTime.MinValue); e.RequestKey = ra.GenerateRequestCachingKey(modDate); var settings = new ResizeSettings(ra.RewrittenInstructions); e.RewrittenQuerystring = settings; e.ResponseHeaders.ContentType = ra.EstimatedContentType; e.SuggestedExtension = ra.EstimatedFileExtension; //A delegate for accessing the source file e.GetSourceImage = new GetSourceImageDelegate(delegate() { return((vf != null) ? vf.Open() : File.Open(ra.RewrittenMappedPath, FileMode.Open, FileAccess.Read, FileShare.Read)); }); //Add delegate for writing the data stream e.ResizeImageToStream = new ResizeImageDelegate(delegate(System.IO.Stream stream) { //This runs on a cache miss or cache invalid. This delegate is preventing from running in more //than one thread at a time for the specified cache key try { if (!ra.ProcessingIndicated) { //Just duplicate the data using (Stream source = e.GetSourceImage()) source.CopyToStream(stream); //4KiB buffer } else { ImageJob j; //Process the image if (vf != null) { j = new ImageJob(vf, stream, settings); } else { j = new ImageJob(ra.RewrittenMappedPath, stream, settings); //Use a physical path to bypass virtual file system } conf.GetImageBuilder().Build(j); } ra.FireJobSuccess(); //Catch not found exceptions } catch (System.IO.FileNotFoundException notFound) { if (notFound.Message.Contains(" assembly ")) { throw; //If an assembly is missing, it should be a 500, not a 404 } //This will be called later, if at all. ra.FireMissing(); throw new ImageMissingException("The specified resource could not be located", "File not found", notFound); } catch (System.IO.DirectoryNotFoundException notFound) { ra.FireMissing(); throw new ImageMissingException("The specified resource could not be located", "File not found", notFound); } catch (Exception ex) { ra.FireJobException(ex); throw; } }); context.Items[conf.ResponseArgsKey] = e; //store in context items //Fire events (for client-side caching plugins) conf.FirePreHandleImage(this, context, e); //Pass the rest of the work off to the caching module. It will handle rewriting/redirecting and everything. //We handle request headers based on what is found in context.Items ICache cache = conf.GetCacheProvider().GetCachingSystem(context, e); //Verify we have a caching system if (cache == null) { throw new ImageProcessingException("Image Resizer: No caching plugin was found for the request"); } cache.Process(context, e); //TODO: Verify that caching systems serves request or transfers to StaticFileHandler }
public void PictureProcess() { int goodsId = JobQueue.GoodsTransferJobPictureProcessQueue.GetItem(goodsTransferJobService.PictrueCdning); if (goodsId == 0) { return; } using (var context = new FxGoodsContext()) { while (goodsId != 0) { var car = context.GoodsTransferInfos.Where(r => r.GoodsTransferInfoId == goodsId).FirstOrDefault(); if (car != null) { string source; string destnation; string destnationmin; int error = 0; string errmsg = ""; foreach (var picture in car.Pictures) { try { source = string.Format(picture.PhysicalPath); destnation = string.Format("{0}{1}", appSettings.CdnPath(), picture.ImageUrl.Replace(@"/", @"\")); destnationmin = string.Format("{0}{1}", appSettings.CdnPath(), picture.MinImageUrl.Replace(@"/", @"\")); var job = new ImageJob(source, destnation, new ResizeSettings() { MaxHeight = 500, MaxWidth = 500, }) { CreateParentDirectory = true }; var jobmin = new ImageJob(source, destnationmin, new ResizeSettings() { MaxHeight = 64, MaxWidth = 64, }) { CreateParentDirectory = true }; ImageBuilder.Current.Build(job); ImageBuilder.Current.Build(jobmin); } catch (Exception ex) { if (string.IsNullOrEmpty(errmsg)) { if (ex.InnerException != null) { errmsg = ex.InnerException.Message; } else { errmsg = ex.Message; } } error++; ex.LogEx(string.Format("{0} {1} {2}", JobKey, "PictureProcess", picture.TransferPictureId)); } } if (error == 0) { goodsTransferJobService.PictrueCdnSuccessd(goodsId); goodsTransferJobService.Publish(goodsId); } else { goodsTransferJobService.PictrueCdnFailed(goodsId, errmsg); } goodsId = JobQueue.GoodsTransferJobPictureProcessQueue.GetItem(goodsTransferJobService.PictrueCdning); } } } }
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); //} }
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> /// 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 ResizeImage(Stream image, int width, int height) { var config = new ImageResizer.Configuration.Config(); var buffer = new MemoryStream(); var job = new ImageJob(image, buffer, new Instructions($"width={width}")); config.Build(job); return buffer; //var resizedImage = new Bitmap(image); //var result = new Bitmap(width, height); //result.SetResolution(resizedImage.HorizontalResolution, resizedImage.VerticalResolution); //using (Graphics graphics = Graphics.FromImage(result)) //{ // graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; // graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; // graphics.DrawImage(resizedImage, 0, 0, width, height); //} //resizedImage.Dispose(); //await _storageHelper.Storefile(result, _thumbnailImage); //return await _storageHelper.GetFile(_thumbnailImage); }
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; }
/// <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 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); }
protected override RequestedAction BuildJob(ImageJob job) { if (base.BuildJob(job) == RequestedAction.Cancel) return RequestedAction.Cancel; Bitmap b = null; try { ResizeSettings s = job.Settings; //Load image b = LoadImage(job.Source, s, job.ResetSourceStream); //Save source path info job.SourcePathData = (b != null && b.Tag != null && b.Tag is BitmapTag) ? ((BitmapTag)b.Tag).Path : null; job.ResultInfo["source.width"] = b.Width; job.ResultInfo["source.height"] = b.Height; //Calucalte the appropriate file extension and mime type if (job.Dest != typeof(Bitmap)){ IEncoder e = this.EncoderProvider.GetEncoder(s, b); if (e != null) { job.ResultInfo["result.ext"] = e.Extension; job.ResultInfo["result.mime"] = e.MimeType; } } if (job.Dest == typeof(IDictionary<string, object>)) { ///They only want information/attributes job.Result = job.ResultInfo; return RequestedAction.Cancel; } //Fire PreAcquireStream(ref dest, settings) to modify 'dest' object dest = job.Dest; this.PreAcquireStream(ref dest, s); job.Dest = dest; if (dest == typeof(Bitmap)) { job.Result = buildToBitmap(b, s, true); //Write to Physical file } else if (dest is string) { //Make physical and resolve variable references all at the same time. job.FinalPath = job.ResolveTemplatedPath(dest as string, delegate(string var) { if ("ext".Equals(var, StringComparison.OrdinalIgnoreCase)) { return job.ResultFileExtension; } if ("width".Equals(var, StringComparison.OrdinalIgnoreCase)) return GetFinalSize(new System.Drawing.Size(b.Width, b.Height), new ResizeSettings(job.Settings)).Width.ToString(NumberFormatInfo.InvariantInfo); if ("height".Equals(var, StringComparison.OrdinalIgnoreCase)) return GetFinalSize(new System.Drawing.Size(b.Width, b.Height), new ResizeSettings(job.Settings)).Height.ToString(NumberFormatInfo.InvariantInfo); return null; }); //If requested, auto-create the parent directory(ies) if (job.CreateParentDirectory) { string dirName = Path.GetDirectoryName(job.FinalPath); if (!Directory.Exists(dirName)) Directory.CreateDirectory(dirName); } System.IO.FileStream fs = new FileStream(job.FinalPath, FileMode.Create, FileAccess.Write); using (fs) { buildToStream(b, fs, s); fs.Flush();//TODO: Switch to .Flush(true) with .NET 4 } //Write to Unknown stream } else if (dest is Stream) { buildToStream(b, (Stream)dest, s); } else throw new ArgumentException("Destination may be a string or Stream.", "Dest"); } finally { //Get the source bitmap's underlying stream (may differ from 'source') Stream underlyingStream = null; if (b != null && b.Tag != null && b.Tag is BitmapTag) underlyingStream = ((BitmapTag)b.Tag).Source; //Close the source bitamp's underlying stream unless it is the same stream (EDIT: or bitmap) we were passed. var closeUnderlyingStream = (b != job.Source && underlyingStream != job.Source && underlyingStream != null); //Dispose the bitmap unless we were passed it. We check for 'null' in case an ImageCorruptedException occured. if (b != null && b != job.Source) b.Dispose(); //Dispose the underlying stream after disposing the bitmap if (closeUnderlyingStream) underlyingStream.Dispose(); } return RequestedAction.Cancel; }
/// <summary> /// Generates the resized image to disk (if needed), then rewrites the request to that location. /// Perform 404 checking before calling this method. Assumes file exists. /// Called during PostAuthorizeRequest /// </summary> /// <param name="context"></param> /// <param name="ra"></param> /// <param name="vf"></param> protected virtual async Task HandleRequest(HttpContext context, HttpModuleRequestAssistant ra, IVirtualFileAsync vf) { if (!ra.CachingIndicated && !ra.ProcessingIndicated) { ra.ApplyRewrittenPath(); //This is needed for both physical and virtual files; only makes changes if needed. if (vf != null) { ra.AssignSFH(); //Virtual files are not served in .NET 4. } return; } //Communicate to the MVC plugin this request should not be affected by the UrlRoutingModule. context.Items[conf.StopRoutingKey] = true; context.Items[conf.ResponseArgsKey] = ""; //We are handling the request ra.EstimateResponseInfo(); //Build CacheEventArgs var e = new AsyncResponsePlan(); var modDate = (vf == null) ? System.IO.File.GetLastWriteTimeUtc(ra.RewrittenMappedPath) : (vf is IVirtualFileWithModifiedDateAsync ? await((IVirtualFileWithModifiedDateAsync)vf).GetModifiedDateUTCAsync() : DateTime.MinValue); e.RequestCachingKey = ra.GenerateRequestCachingKey(modDate); var settings = new ResizeSettings(ra.RewrittenInstructions); e.RewrittenQuerystring = settings; e.EstimatedContentType = ra.EstimatedContentType; e.EstimatedFileExtension = ra.EstimatedFileExtension; //A delegate for accessing the source file e.OpenSourceStreamAsync = async delegate() { return((vf != null) ? await vf.OpenAsync() : File.Open(ra.RewrittenMappedPath, FileMode.Open, FileAccess.Read, FileShare.Read)); }; //Add delegate for writing the data stream e.CreateAndWriteResultAsync = async delegate(System.IO.Stream stream, IAsyncResponsePlan plan) { //This runs on a cache miss or cache invalid. This delegate is preventing from running in more //than one thread at a time for the specified cache key try { if (!ra.ProcessingIndicated) { //Just duplicate the data using (Stream source = await e.OpenSourceStreamAsync()) await source.CopyToAsync(stream); //4KiB buffer } else { MemoryStream inBuffer = null; using (var sourceStream = vf != null ? await vf.OpenAsync() : File.Open(ra.RewrittenMappedPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { inBuffer = new MemoryStream(sourceStream.CanSeek ? (int)sourceStream.Length : 128 * 1024); await sourceStream.CopyToAsync(inBuffer); } inBuffer.Seek(0, SeekOrigin.Begin); var outBuffer = new MemoryStream(32 * 1024); //Handle I/O portions of work asynchronously. var j = new ImageJob { Instructions = new Instructions(settings), SourcePathData = vf != null ? vf.VirtualPath : ra.RewrittenVirtualPath, Dest = outBuffer, Source = inBuffer }; await conf.GetImageBuilder().BuildAsync(j, int.MaxValue, CancellationToken.None); outBuffer.Seek(0, SeekOrigin.Begin); await outBuffer.CopyToAsync(stream); } ra.FireJobSuccess(); //Catch not found exceptions } catch (System.IO.FileNotFoundException notFound) { if (notFound.Message.Contains(" assembly ")) { throw; //If an assembly is missing, it should be a 500, not a 404 } //This will be called later, if at all. ra.FireMissing(); throw new ImageMissingException("The specified resource could not be located", "File not found", notFound); } catch (System.IO.DirectoryNotFoundException notFound) { ra.FireMissing(); throw new ImageMissingException("The specified resource could not be located", "File not found", notFound); } catch (Exception ex) { ra.FireJobException(ex); throw; } }; //All bad from here down.... context.Items[conf.ResponseArgsKey] = e; //store in context items //Fire events (for client-side caching plugins) conf.FirePreHandleImageAsync(this, context, e); //Pass the rest of the work off to the caching module. It will handle rewriting/redirecting and everything. //We handle request headers based on what is found in context.Items IAsyncTyrantCache cache = conf.GetAsyncCacheFor(context, e); //Verify we have a caching system if (cache == null) { throw new ImageProcessingException("Image Resizer: No async caching plugin was found for the request"); } await cache.ProcessAsync(context, e); }
/// <summary> /// Resizes and processes the specified source image and stores the encoded result in the specified destination. /// If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior. /// </summary> /// <param name="source">May be an instance of string (a physical path or app-relative virtual path), VirtualFile, IVirtualBitmapFile, HttpPostedFile, Bitmap, Image, or Stream. App-relative virtual paths will use the VirtualPathProvider system</param> /// <param name="dest">May be a physical path (string), or a Stream instance. Does not have to be seekable.</param> /// <param name="instructions">Resizing and processing command to apply to the image.</param> public virtual ImageJob Build(object source, object dest, Instructions instructions) { var j = new ImageJob(source, dest, instructions, true, false); Build(j); return j; }
/// <summary> /// The most flexible method for processing an image /// </summary> /// <param name="job"></param> /// <returns></returns> public virtual ImageJob Build(ImageJob job) { if (job == null) throw new ArgumentNullException("job", "ImageJob parameter null. Cannot Build a null ImageJob instance"); //Clone and filter settings FIRST, before calling plugins. ResizeSettings s = job.Settings == null ? new ResizeSettings() : new ResizeSettings(job.Settings); if (SettingsModifier != null) s = SettingsModifier.Modify(s); job.Settings = s; try { //Allow everything else to be overriden if (BuildJob(job) != RequestedAction.Cancel) throw new ImageProcessingException("Nobody did the job"); return job; } finally { //Follow the dispose requests if (job.DisposeSourceObject && job.Source is IDisposable && job.Source != null) ((IDisposable)job.Source).Dispose(); if (job.DisposeDestinationStream && job.Dest is IDisposable && job.Dest != null) ((IDisposable)job.Dest).Dispose(); } }
/// <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(); } }
public virtual Bitmap Build(object source, ResizeSettings settings, bool disposeSource) { ImageJob j = new ImageJob(source, typeof(Bitmap), settings, disposeSource, false); Build(j); return j.Result as Bitmap; }
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; }
private static async Task<string> ResizeImage(Stream streamInput, CloudBlockBlob blobOutput, ImageSize size) { streamInput.Position = 0; using (var memoryStream = new MemoryStream()) { // use a memory stream, since using the blob stream directly causes InvalidOperationException due to the way image resizer works var instructions = new Instructions(imageDimensionsTable[size]); var job = new ImageJob(streamInput, memoryStream, instructions, disposeSource: false, addFileExtension: false); // use the advanced version of resize so that we can get the content type var result = ImageBuilder.Current.Build(job); memoryStream.Position = 0; await blobOutput.UploadFromStreamAsync(memoryStream); var contentType = result.ResultMimeType; blobOutput.Properties.ContentType = contentType; blobOutput.SetProperties(); return contentType; } }
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(); } } }