public ImageResizeParameters(double maxWidth, double maxHeight, ImageResizeMode mode) { Mode = mode; MaxWidth = maxWidth; MaxHeight = maxHeight; Quality = 90; }
private ImageResizeTransform CreateTransform(int width, int height, ImageResizeMode mode) { return new ImageResizeTransform() { Width = width, Height = height, Mode = mode }; }
/// <summary> /// Resize image<br/> /// 改变图片大小<br/> /// </summary> /// <param name="image">Original image</param> /// <param name="width">Width</param> /// <param name="height">Height</param> /// <param name="mode">Resize mode</param> /// <param name="background">Background, default is transparent</param> /// <returns></returns> /// <example> /// <code language="cs"> /// var newImage = oldImage.Resize(100, 100, ImageResizeMode.Fixed); /// </code> /// </example> public static Image Resize(this Image image, int width, int height, ImageResizeMode mode, Color?background = null) { var src = new Rectangle(0, 0, image.Width, image.Height); var dst = new Rectangle(0, 0, width, height); // Calculate destination rectangle by resize mode if (mode == ImageResizeMode.Fixed) { } else if (mode == ImageResizeMode.ByWidth) { height = (int)((decimal)src.Height / src.Width * dst.Width); dst.Height = height; } else if (mode == ImageResizeMode.ByHeight) { width = (int)((decimal)src.Width / src.Height * dst.Height); dst.Width = width; } else if (mode == ImageResizeMode.Cut) { if ((decimal)src.Width / src.Height > (decimal)dst.Width / dst.Height) { src.Width = (int)((decimal)dst.Width / dst.Height * src.Height); src.X = (image.Width - src.Width) / 2; // Cut left and right } else { src.Height = (int)((decimal)dst.Height / dst.Width * src.Width); src.Y = (image.Height - src.Height) / 2; // Cut top and bottom } } else if (mode == ImageResizeMode.Padding) { if ((decimal)src.Width / src.Height > (decimal)dst.Width / dst.Height) { dst.Height = (int)((decimal)src.Height / src.Width * dst.Width); dst.Y = (height - dst.Height) / 2; // Padding left and right } else { dst.Width = (int)((decimal)src.Width / src.Height * dst.Height); dst.X = (width - dst.Width) / 2; // Padding top and bottom } } // Draw new image var newImage = new Bitmap(width, height); using (var graphics = Graphics.FromImage(newImage)) { // Set smoothing mode graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; // Set background color graphics.Clear(background ?? Color.Transparent); // Render original image with the calculated rectangle graphics.DrawImage(image, dst, src, GraphicsUnit.Pixel); } return(newImage); }
/// <summary> /// Resize an image to new width and height /// </summary> /// <param name="img">The image to be resized</param> /// <param name="ImageResizeMode">The mode to use when resizing the image</param> /// <param name="bounds">The new image width and height</param> /// <param name="interpolateMode">The interpolation mode to be used when resizing the image</param> /// <returns>The resized image</returns> public static Image ResizeImage(this Image img, ImageResizeMode mode, Size bounds, Color baseColor, InterpolationMode interpolateMode, SmoothingMode smoothingMode) { if (mode == ImageResizeMode.Scale) { bounds = Images.AspectSize(img, bounds.Width, bounds.Height); } Image sizedImg = new Bitmap(bounds.Width, bounds.Height); Graphics g = Graphics.FromImage(sizedImg); g.InterpolationMode = interpolateMode; g.SmoothingMode = smoothingMode; if (baseColor != null && baseColor != Color.Empty && baseColor != Color.Transparent) { g.FillRectangle(new SolidBrush(baseColor), 0, 0, bounds.Width, bounds.Height); } if (mode == ImageResizeMode.Stretch || mode == ImageResizeMode.Scale) { g.DrawImage(img, 0, 0, bounds.Width, bounds.Height); } else if (mode == ImageResizeMode.ScaleCenter || mode == ImageResizeMode.ScaleFit) { Size aspectSize = Images.AspectSize(img, bounds.Width, bounds.Height, (mode == ImageResizeMode.ScaleFit)); int xloc = ((aspectSize.Width + bounds.Width) / 2) - aspectSize.Width; int yloc = ((aspectSize.Height + bounds.Height) / 2) - aspectSize.Height; g.DrawImage(img, xloc, yloc, aspectSize.Width, aspectSize.Height); } return(sizedImg); }
public virtual byte[] GetResizedBytes(Stream imageStream, string extension, double maxWidth, double maxHeight, ImageResizeMode mode) { using (Bitmap original = new Bitmap(imageStream)) { var ms = new MemoryStream(); Resize(extension, original, maxWidth, maxHeight, mode, ms); return ms.GetBuffer(); } }
public ImageHttpPostedFileBase(Stream stream, string contentType, string fileName, Size imageThumbnailSize, int ImageQuality, ImageResizeMode imageResizeMode) { this.stream = stream; this.contentType = contentType; this.fileName = fileName; this.ImageQuality = ImageQuality; this.ImageThumbnailSize = imageThumbnailSize; this.ImageResizeMode = imageResizeMode; }
private ImageResizeTransform CreateTransform(int width, int height, ImageResizeMode mode) { return(new ImageResizeTransform() { Width = width, Height = height, Mode = mode }); }
/// <summary> /// Create new instance of image filtration parameters /// </summary> /// <param name="ctx"></param> /// <param name="fileName"></param> public ImageFiltrationParameters(Image input, int w, int h, ImageResizeMode mode) { this.TargetWidth = w; this.TargetHeight = h; this.Mode = mode; this.IsProcessResize = false; this.ImageOffsetAndSize = RectangleF.Empty; this.Validate(input); }
/// <summary> /// Resizes the specified image. /// </summary> /// <param name="image">The input image.</param> /// <param name="width">The output image width or 0 if the specified resize mode is <see cref="ImageResizeMode.FixHeight"/>.</param> /// <param name="height">The output image height or 0 if the specified resize mode is <see cref="ImageResizeMode.FixWidth"/>.</param> /// <param name="resizeMode">The <see cref="ImageResizeMode"/>.</param> /// <param name="keepTransparency">A value indicating whether to keep transparency information from the source image.</param> /// <param name="backgroundColor">The background color.</param> /// <param name="barColor">The color of the bars that are used when the aspect ratio of the input image differs from the specified output dimensions.</param> /// <returns>The resized <see cref="Bitmap"/>.</returns> /// <exception cref="ArgumentNullException">The specified <paramref name="image"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// The specified <paramref name="width"/> is zero or negative. /// -or- /// The specified <paramref name="height"/> is zero or negative. /// </exception> public static Bitmap ResizeImage(Image image, int width, int height, ImageResizeMode resizeMode, bool keepTransparency, Color backgroundColor, Color barColor) { Check.Require <ArgumentNullException>(barColor != null, "barColor"); Check.Require <ArgumentNullException>(backgroundColor != null, "backgroundColor"); using (Brush backgroundBrush = new SolidBrush(backgroundColor)) using (Brush barBrush = new SolidBrush(barColor)) { return(ResizeImage(image, width, height, resizeMode, keepTransparency, backgroundBrush, barBrush)); } }
/// <summary>Returns the path to an image handler that resizes the given image to the appropriate size.</summary> /// <param name="imageUrl">The image to resize.</param> /// <param name="width">The maximum width.</param> /// <param name="height">The maximum height.</param> /// <param name="mode">How to fit the image</param> /// <returns>The path to a handler that performs resizing of the image.</returns> public static string GetResizedImageUrl(string imageUrl, double width, double height, ImageResizeMode mode) { string fileExtension = VirtualPathUtility.GetExtension(Url.PathPart(imageUrl)); bool isAlreadyImageHandler = string.Equals(fileExtension, ".ashx", StringComparison.OrdinalIgnoreCase); if (isAlreadyImageHandler) return Url.ToAbsolute(imageUrl); Url url = ImageHandlerUrl.SetQueryParameter("img", N2.Context.Current.ManagementPaths.ResolveResourceUrl(imageUrl)); if (width > 0) url = url.SetQueryParameter("w", (int)width); if (height > 0) url = url.SetQueryParameter("h", (int)height); url = url.AppendQuery("m", mode.ToString()); return url; }
public virtual bool Resize(Stream inputStream, string extension, double maxWidth, double maxHeight, ImageResizeMode mode, Stream outputStream) { using (Bitmap original = new Bitmap(inputStream)) { //if (original.Width < maxWidth && original.Height < maxHeight) //{ // TransferBetweenStreams(inputStream, outputStream); // return true; //} Resize(extension, original, maxWidth, maxHeight, mode, outputStream); return true; } }
/// <summary> /// Gets a resized image based on the formatting criteria allowed by the Xbox Music service. /// </summary> /// <param name="width">Image width in pixels.</param> /// <param name="height">Image height in pixels.</param> /// <param name="mode">The mode with wich to resize the image.</param> /// <param name="backgroundColor"> /// HTML-compliant color for letterbox resize mode background. Hex values must start with a #. /// Can also use color names, such as "green". Defaults to an empty string. /// </param> /// <returns>A string with the URL for the requested image specifications.</returns> public string GetImage(int width, int height, ImageResizeMode mode = ImageResizeMode.Crop, string backgroundColor = "") { var modeString = Enum.GetName(typeof(ImageResizeMode), mode).ToLower(); switch (mode) { case ImageResizeMode.Letterbox: return string.Format("{0}&w={1}&h={2}&mode={3}&background={4}", ImageUrl, width, height, modeString, backgroundColor.Replace("#", "%23")); case ImageResizeMode.Scale: return string.Format("{0}&w={1}&h={2}&mode={3}", ImageUrl, width, height, modeString); default: return string.Format("{0}&w={1}&h={2}", ImageUrl, width, height); } }
/// <summary> /// Gets a resized image based on the formatting criteria allowed by the Xbox Music service. /// </summary> /// <param name="width">Image width in pixels.</param> /// <param name="height">Image height in pixels.</param> /// <param name="mode">The mode with wich to resize the image.</param> /// <param name="backgroundColor"> /// HTML-compliant color for letterbox resize mode background. Hex values must start with a #. /// Can also use color names, such as "green". Defaults to an empty string. /// </param> /// <returns>A string with the URL for the requested image specifications.</returns> public string GetImage(int width, int height, ImageResizeMode mode = ImageResizeMode.Crop, string backgroundColor = "") { var modeString = Enum.GetName(typeof(ImageResizeMode), mode).ToLower(); switch (mode) { case ImageResizeMode.Letterbox: return(string.Format("{0}&w={1}&h={2}&mode={3}&background={4}", ImageUrl, width, height, modeString, backgroundColor.Replace("#", "%23"))); case ImageResizeMode.Scale: return(string.Format("{0}&w={1}&h={2}&mode={3}", ImageUrl, width, height, modeString)); default: return(string.Format("{0}&w={1}&h={2}", ImageUrl, width, height)); } }
public void Save_ResizeMode(ImageResizeMode mode) { var filename = "lena.png"; using (var resizer = new ImageResizer(GetSource(filename))) { resizer.ResizeMode = mode; resizer.Width = 256; var ext = Io.Get(filename).Extension; var dest = SavePath(resizer, "mode", ext); resizer.Save(dest); Assert.That(Io.Exists(dest), Is.True); } }
/// <summary> /// Creates a high quality resized version of the provided image /// </summary> /// <param name="original">The original image</param> /// <param name="newWidth">The width of the new image</param> /// <param name="newHeight">The height of the new image</param> /// <param name="resizeMode">Resize mode (defines stretching)</param> /// <param name="padding">Padding around the new image (can be - and often is - negative)</param> /// <param name="backgroundColor">Background color for areas not overlapped by the original image (due to stretch or padding)</param> /// <returns>The image in its new size</returns> public static Image ResizeImage(Image original, int newWidth, int newHeight, ImageResizeMode resizeMode, int padding, Color backgroundColor) { var bmp = new Bitmap(newWidth, newHeight); var g = Graphics.FromImage(bmp); g.CompositingQuality = CompositingQuality.HighQuality; g.InterpolationMode = InterpolationMode.High; g.SmoothingMode = SmoothingMode.HighQuality; g.Clear(backgroundColor); // This is the area actually used by the resized image int targetWidth = newWidth - (padding * 2); int targetHeight = newHeight - (padding * 2); var renderRect = new Rectangle(0, 0, newWidth, newHeight); switch (resizeMode) { case ImageResizeMode.Stretch: renderRect = new Rectangle((int)((newWidth - targetWidth) / 2), (int)((newHeight - targetHeight) / 2), targetWidth, targetHeight); break; case ImageResizeMode.StretchToFillKeepProportions: decimal verticalFactor = (decimal)targetHeight / (decimal)original.Height; decimal horizontalFactor = (decimal)targetWidth / (decimal)original.Width; var factor = Math.Min(verticalFactor, horizontalFactor); int renderHeight = (int)(original.Height * factor); int renderWidth = (int)(original.Width * factor); renderRect = new Rectangle((int)((newWidth - renderWidth) / 2), (int)((newHeight - renderHeight) / 2), renderWidth, renderHeight); break; case ImageResizeMode.StretchToNearestEdge: decimal verticalFactor2 = (decimal)targetHeight / (decimal)original.Height; decimal horizontalFactor2 = (decimal)targetWidth / (decimal)original.Width; var factor2 = Math.Max(verticalFactor2, horizontalFactor2); int renderHeight2 = (int)(original.Height * factor2); int renderWidth2 = (int)(original.Width * factor2); renderRect = new Rectangle((int)((newWidth - renderWidth2) / 2), (int)((newHeight - renderHeight2) / 2), renderWidth2, renderHeight2); break; } g.DrawImage(original, renderRect); return(bmp); }
/// <summary> /// 缩放图片 /// </summary> /// <param name="image">原图片</param> /// <param name="width">宽度</param> /// <param name="height">高度</param> /// <param name="mode">缩放模式</param> /// <param name="background">背景颜色,默认是透明</param> /// <returns></returns> public static Image Resize(this Image image, int width, int height, ImageResizeMode mode, Color? background = null) { var src = new Rectangle(0, 0, image.Width, image.Height); var dst = new Rectangle(0, 0, width, height); // 根据模式调整缩放到的大小和位置 if (mode == ImageResizeMode.Fixed) { } else if (mode == ImageResizeMode.ByWidth) { height = (int)((decimal)src.Height / src.Width * dst.Width); dst.Height = height; } else if (mode == ImageResizeMode.ByHeight) { width = (int)((decimal)src.Width / src.Height * dst.Height); dst.Width = width; } else if (mode == ImageResizeMode.Cut) { if ((decimal)src.Width / src.Height > (decimal)dst.Width / dst.Height) { src.Width = (int)((decimal)dst.Width / dst.Height * src.Height); src.X = (image.Width - src.Width) / 2; // 切除原图片左右 } else { src.Height = (int)((decimal)dst.Height / dst.Width * src.Width); src.Y = (image.Height - src.Height) / 2; // 切除原图片上下 } } else if (mode == ImageResizeMode.Padding) { if ((decimal)src.Width / src.Height > (decimal)dst.Width / dst.Height) { dst.Height = (int)((decimal)src.Height / src.Width * dst.Width); dst.Y = (height - dst.Height) / 2; // 扩展原图片左右 } else { dst.Width = (int)((decimal)src.Width / src.Height * dst.Height); dst.X = (width - dst.Width) / 2; // 扩展原图片上下 } } // 缩放到新图片上 var newImage = new Bitmap(width, height); using (var graphics = Graphics.FromImage(newImage)) { // 设置高质量缩放 graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; // 设置背景色 graphics.Clear(background ?? Color.Transparent); // 在新图片上描画原图片 graphics.DrawImage(image, dst, src, GraphicsUnit.Pixel); } return newImage; }
/// <summary> /// Resize style /// </summary> /// <param name="name"> Style name </param> /// <param name="resizeWidth"> Max width (0 for auto) </param> /// <param name="resizeHeight"> Max height (0 for auto) </param> /// <param name="resizeMode"> Resize mode </param> public HasImageStyleAttribute( string name, int resizeWidth, int resizeHeight, ImageResizeMode resizeMode = ImageResizeMode.PreserveAspectRatio, Resampler resampler = Resampler.Auto, int quality = 100) : base(name) { var resizeOptions = new ImageResizeOptions { Width = resizeWidth, Height = resizeHeight, Mode = resizeMode }; var decodeOptions = new ImageEncodeOptions { Quality = quality }; Style = new ImageStyle(name, resizeOptions, decodeOptions); }
/// <summary> /// The get image. /// </summary> /// <param name="imageId"> /// The image id. /// </param> /// <param name="width"> /// The width. /// </param> /// <param name="height"> /// The height. /// </param> /// <param name="imageResizeMode"> /// The image resize mode. /// </param> /// <param name="watermarks"> /// The watermarks. /// </param> /// <returns> /// The <see cref="ActionResult"/>. /// </returns> private ActionResult GetImage(int?imageId, int?width, int?height, ImageResizeMode imageResizeMode, IEnumerable <IImageWatermark> watermarks) { Image image = null; if (imageId.HasValue) { image = this.ImageService.GetQueryable().SingleOrDefault(a => a.Id == imageId); } var settings = new ImageProcessorSetting { ImageResizeMode = imageResizeMode, FeelBackground = true, BackgrounBrush = Brushes.White }; settings.Watermarks.AddRange(watermarks); var imageWidth = width.HasValue ? (double)width : double.MaxValue; var imageHeight = height.HasValue ? (double)height : double.MaxValue; var mapedImageFile = this.Server.MapPath("~/Images/no-image.jpg"); if (image != null && System.IO.File.Exists(HostingEnvironment.MapPath(image.Source))) { mapedImageFile = this.Server.MapPath(image.Source); var originalSize = new Size(image.Width, image.Height); var targetSize = new Size(imageWidth, imageHeight); var imageSize = width.HasValue && height.HasValue ? new Size(imageWidth, imageHeight) : this.ImageProcessor.ComputeImageAspectSize(originalSize, targetSize); return(this.File(this.ImageProcessor.ProcesImage(mapedImageFile, imageSize, settings), "image/jpeg")); } var size = width.HasValue ? new Size(imageWidth, imageWidth) : new Size(imageHeight, imageHeight); return(this.File(this.ImageProcessor.ProcesImage(mapedImageFile, size, settings), "image/jpeg")); }
private Image <Rgba32> Transform(int width, int height, ImageResizeMode mode) { var transformer = new ImageSharpImageTransformer(); var imageStyle = new ImageStyle("test") { ResizeOptions = new ImageResizeOptions { Width = width, Height = height, Mode = mode } }; var configuration = Configuration.Default; var bytes = TestFile.Create(TestImages.Jpeg.Lake).Bytes; var image = SixLabors.ImageSharp.Image.Load(configuration, bytes); transformer.Transform(image, imageStyle); return(image); }
public static Size GetNewImageSize(int imgWidth, int imgHeight, ImageResizeMode resizeMode = ImageResizeMode.OnMinSide, int containerWidth = DEFAULT_CONTAINER_WIDTH, int containerHeight = DEFAULT_CONTAINER_HEIGHT) { double relX = (double)imgWidth / (double)containerWidth; double relY = (double)imgHeight / (double)containerHeight; switch (resizeMode) { case ImageResizeMode.OnMinSide: if ((relX >= relY) && (relY > 1.0)) { imgHeight = containerHeight; imgWidth = (relX > relY) ? (int)((double)imgWidth / relY) : containerWidth; } else if ((relY > relX) && (relX > 1.0)) { imgWidth = containerWidth; imgHeight = (int)((double)imgHeight / relX); } break; case ImageResizeMode.OnMaxSide: if ((relX >= relY) && (relY > 1.0)) { imgWidth = containerWidth; imgHeight = (relX > relY) ? (int)((double)imgHeight / relX) : containerHeight; } else if ((relY > relX) && (relX > 1.0)) { imgHeight = containerHeight; imgWidth = (int)((double)imgWidth / relY); } break; } return(new Size(imgWidth, imgHeight)); }
/// <summary> /// Creates a high quality resized version of the provided image /// </summary> /// <param name="original">The original image</param> /// <param name="newWidth">The width of the new image</param> /// <param name="newHeight">The height of the new image</param> /// <param name="resizeMode">Resize mode (defines stretching)</param> /// <returns>The image in its new size</returns> public static Image ResizeImage(Image original, int newWidth, int newHeight, ImageResizeMode resizeMode) { return ResizeImage(original, newWidth, newHeight, resizeMode, 0, Color.Transparent); }
public static Image CreateThumbnail(Image Source, int MaxWidth, int MaxHeight, ImageResizeMode Resize = ImageResizeMode.Trim) { int newImageWidth = MaxWidth; int newImageHeight = MaxHeight; int xpos = 0; int ypos = 0; int width = MaxWidth; int height = (int)(((double)MaxWidth / Source.Width) * Source.Height); if (height > MaxHeight) { ypos = 0; height = MaxHeight; width = (int)(((double)MaxHeight / Source.Height) * Source.Width); } if (Resize == ImageResizeMode.Crop) { width = MaxWidth; height = (int)(((double)MaxWidth / Source.Width) * Source.Height); if (height < MaxHeight) { ypos = 0; height = MaxHeight; width = (int)(((double)MaxHeight / Source.Height) * Source.Width); } } if (Resize != ImageResizeMode.Stretch) { ypos = (MaxHeight - height) / 2; xpos = (MaxWidth - width) / 2; } if (Resize == ImageResizeMode.Trim) { newImageHeight = height; newImageWidth = width; } if (Resize == ImageResizeMode.BestFit) { xpos = 0; ypos = 0; newImageHeight = height; newImageWidth = width; } if (Resize == ImageResizeMode.CenterTop) { height -= ypos; ypos = 0; newImageHeight = height; } if(Resize == ImageResizeMode.Stretch) { xpos = 0; ypos = 0; width = newImageWidth; height= newImageHeight; } //return Source.GetThumbnailImage(width, height, null, IntPtr.Zero); Image thumb = new Bitmap(newImageWidth, newImageHeight); using (Graphics g = Graphics.FromImage(thumb)) { g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(Source, xpos, ypos, width, height); } return thumb; }
private void Resize(string extension, Bitmap original, double maxWidth, double maxHeight, ImageResizeMode mode, Stream output) { Bitmap resized; if (mode == ImageResizeMode.Fit) { double resizeRation = GetResizeRatio(original, maxWidth, maxHeight); int newWidth = (int)Math.Round(original.Width * resizeRation); int newHeight = (int)Math.Round(original.Height * resizeRation); resized = new Bitmap(newWidth, newHeight, original.PixelFormat); } else { resized = new Bitmap((int)maxWidth, (int)maxHeight, original.PixelFormat); } resized.SetResolution(original.HorizontalResolution, original.VerticalResolution); Graphics g = CreateGraphics(original, ref resized, extension); using (g) { g.PageUnit = GraphicsUnit.Pixel; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.CompositingMode = CompositingMode.SourceCopy; g.CompositingQuality = CompositingQuality.HighQuality; using (ImageAttributes attr = new ImageAttributes()) { attr.SetWrapMode(WrapMode.TileFlipXY); Rectangle destinationFrame = mode == ImageResizeMode.Fill ? GetFillDestinationRectangle(original.Size, resized.Size) : new Rectangle(Point.Empty, resized.Size); g.DrawImage(original, destinationFrame, 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attr); } resized.Save(output, original.RawFormat); } }
/// <summary> /// Actual method that resizes the image with a specific resize mode /// </summary> /// <param name="file">the file</param> /// <param name="width">resize width</param> /// <param name="height">resize height</param> /// <param name="mode">resize mode</param> /// <param name="context"></param> /// <param name="eTag"></param> protected void ResizeAndWrite(string file, int width, int height, ImageResizeMode mode, HttpContext context, string eTag, bool useCaching) { if (string.IsNullOrEmpty(file)) return; if (file.Substring(0, 1).ToLower() == "/") file = file.Substring(1); // strip the '/' from '/content' else if (file.Substring(0, 2).ToLower() == "\\") file = file.Substring(2); // strip the '\\' from '\\content' file = file.Replace("/", "\\"); string absolutePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file); if (File.Exists(absolutePath) && ImageHelper.IsImage(absolutePath)) { string extension = ImageHelper.GetExtension(file); Image image; if (useCaching) { var baseCachePath = imageCachePath; Directory.CreateDirectory(baseCachePath); // niet erg als dit vaker gebeurt; doet niets als dir al bestaat // Maak hash op basis van de uniek aangevraagde URL en de laatste bewerkdatum en tijd van het originele bestand string cachedFileName = CalculateHash(context.Request.Url.ToString().ToLowerInvariant() + File.GetLastWriteTime(absolutePath).ToString(CultureInfo.InvariantCulture)) + "." + extension; var fullCachedImagePath = Path.Combine(baseCachePath, cachedFileName); if (File.Exists(fullCachedImagePath)) { image = Image.FromFile(fullCachedImagePath); } else { image = ImageHelper.Resize(absolutePath, width, height, mode); image.Save(fullCachedImagePath); } } else { image = ImageHelper.Resize(absolutePath, width, height, mode); } MemoryStream stream = new MemoryStream(); if (extension == "png") { context.Response.ContentType = "image/png"; image.Save(stream, ImageFormat.Png); } else { ImageCodecInfo imageCodecInfo = GetEncoder(ImageFormat.Jpeg); Encoder encoder = Encoder.Quality; EncoderParameters encoderParameters = new EncoderParameters(1); EncoderParameter encoderParameter = new EncoderParameter(encoder, 100L); encoderParameters.Param[0] = encoderParameter; context.Response.ContentType = "image/jpg"; image.Save(stream, imageCodecInfo, encoderParameters); } byte[] buffer = new byte[stream.Length]; stream.Position = 0; stream.Read(buffer, 0, (int)stream.Length); context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.Cache.SetETag(eTag); context.Response.Cache.SetExpires(DateTime.Now.AddYears(1)); context.Response.OutputStream.Write(buffer, 0, buffer.Length); return; } // not a file if (context.Request.Url.DnsSafeHost != "localhost") { // only throw exception online throw new HttpException(404, string.Format("InvalidImage {0}", absolutePath)); } }
private bool Resize(string physicalImagePath, double maxWidth, double maxHeight, ImageResizeMode mode, Stream outputStream) { if (physicalImagePath == null) throw new ArgumentNullException("imagePath"); if (!File.Exists(physicalImagePath)) return false; using (Bitmap original = new Bitmap(physicalImagePath)) { //if (original.Width < maxWidth && original.Height < maxHeight) //{ // using (var fs = File.OpenRead(physicalImagePath)) // { // TransferBetweenStreams(fs, outputStream); // } // return true; //} Resize(Path.GetExtension(physicalImagePath), original, maxWidth, maxHeight, mode, outputStream); return true; } }
/// <summary> /// Resizes the specified image. /// </summary> /// <param name="image">The input image.</param> /// <param name="width">The output image width or 0 if the specified resize mode is <see cref="ImageResizeMode.FixHeight"/>.</param> /// <param name="height">The output image height or 0 if the specified resize mode is <see cref="ImageResizeMode.FixWidth"/>.</param> /// <param name="resizeMode">The <see cref="ImageResizeMode"/>.</param> /// <param name="keepTransparency">A value indicating whether to keep transparency information from the source image.</param> /// <param name="backgroundColor">The background color.</param> /// <param name="barColor">The color of the bars that are used when the aspect ratio of the input image differs from the specified output dimensions.</param> /// <returns>The resized <see cref="Bitmap"/>.</returns> /// <exception cref="ArgumentNullException">The specified <paramref name="image"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// The specified <paramref name="width"/> is zero or negative. /// -or- /// The specified <paramref name="height"/> is zero or negative. /// </exception> public static Bitmap ResizeImage(Image image, int width, int height, ImageResizeMode resizeMode, bool keepTransparency, Color backgroundColor, Color barColor) { Check.Require<ArgumentNullException>(barColor != null, "barColor"); Check.Require<ArgumentNullException>(backgroundColor != null, "backgroundColor"); using (Brush backgroundBrush = new SolidBrush(backgroundColor)) using (Brush barBrush = new SolidBrush(barColor)) { return ResizeImage(image, width, height, resizeMode, keepTransparency, backgroundBrush, barBrush); } }
/// <summary> /// Resizes the specified image. /// </summary> /// <param name="image">The input image.</param> /// <param name="width">The output image width or 0 if the specified resize mode is <see cref="ImageResizeMode.FixHeight"/>.</param> /// <param name="height">The output image height or 0 if the specified resize mode is <see cref="ImageResizeMode.FixWidth"/>.</param> /// <param name="resizeMode">The <see cref="ImageResizeMode"/>.</param> /// <param name="keepTransparency">A value indicating whether to keep transparency information from the source image.</param> /// <param name="backgroundBrush">The background brush.</param> /// <param name="barBrush">The brush of the bars that are used when the aspect ratio of the input image differs from the specified output dimensions.</param> /// <returns>The resized <see cref="Bitmap"/>.</returns> /// <exception cref="ArgumentNullException">The specified <paramref name="image"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// The specified <paramref name="width"/> is zero or negative. /// -or- /// The specified <paramref name="height"/> is zero or negative. /// </exception> public static Bitmap ResizeImage(Image image, int width, int height, ImageResizeMode resizeMode, bool keepTransparency, Brush backgroundBrush, Brush barBrush) { Check.Require<ArgumentNullException>(image != null, "image"); Check.Require<ArgumentOutOfRangeException>(resizeMode == ImageResizeMode.FixHeight || width > 0, "width"); Check.Require<ArgumentOutOfRangeException>(resizeMode != ImageResizeMode.FixHeight || width == 0, "width"); Check.Require<ArgumentOutOfRangeException>(resizeMode == ImageResizeMode.FixWidth || height > 0, "height"); Check.Require<ArgumentOutOfRangeException>(resizeMode != ImageResizeMode.FixWidth || height == 0, "height"); Check.Require<ArgumentNullException>(backgroundBrush != null, "backgroundBrush"); Check.Require<ArgumentNullException>(barBrush != null, "barBrush"); // Imply operation flags from the specified resize mode. bool maintainAspectRatio = false; bool allowUpscaling = false; bool fixWidth = false; bool fixHeight = false; bool fill = false; bool bars = false; if (resizeMode == ImageResizeMode.Constrain) { maintainAspectRatio = true; } else if (resizeMode == ImageResizeMode.ExtendConstrained) { maintainAspectRatio = true; bars = true; } else if (resizeMode == ImageResizeMode.ExtendScaled) { maintainAspectRatio = true; allowUpscaling = true; bars = true; } else if (resizeMode == ImageResizeMode.Fill) { maintainAspectRatio = true; allowUpscaling = true; fill = true; } else if (resizeMode == ImageResizeMode.FixHeight) { maintainAspectRatio = true; allowUpscaling = true; fixHeight = true; } else if (resizeMode == ImageResizeMode.FixWidth) { maintainAspectRatio = true; allowUpscaling = true; fixWidth = true; } else if (resizeMode == ImageResizeMode.Scale) { maintainAspectRatio = true; allowUpscaling = true; } else if (resizeMode == ImageResizeMode.Stretch) { allowUpscaling = true; } if (width < 1 && !fixHeight) { throw new ArgumentOutOfRangeException("width", ArgumentOutOfRangeException_MustEqualOneOrLarger); } else if (height < 1 && !fixWidth) { throw new ArgumentOutOfRangeException("height", ArgumentOutOfRangeException_MustEqualOneOrLarger); } float inputWidth = image.Width; float inputHeight = image.Height; float outputWidth = width; float outputHeight = height; float renderLeft = 0; float renderTop = 0; float renderWidth = 0; float renderHeight = 0; Bitmap outputImage = null; if (maintainAspectRatio) { // Fill the image to completely cover the requested output dimensions, // at the cost of some probable cropped image data. if (fill) { renderWidth = inputWidth * (outputWidth / inputWidth); renderHeight = inputHeight * (outputWidth / inputWidth); if (renderHeight < outputHeight) { renderWidth *= outputHeight / renderHeight; renderHeight *= outputHeight / renderHeight; } } else { // Calculate the render dimensions maintaining the aspect ratio. renderWidth = inputWidth; renderHeight = inputHeight; if (renderWidth < outputWidth && allowUpscaling) { renderHeight *= outputWidth / renderWidth; renderWidth = outputWidth; } if (renderHeight < outputHeight && allowUpscaling) { renderWidth *= outputHeight / renderHeight; renderHeight = outputHeight; } if (renderWidth > outputWidth && !fixHeight) { renderHeight *= outputWidth / renderWidth; renderWidth = outputWidth; } if (renderHeight > outputHeight && !fixWidth) { renderWidth *= outputHeight / renderHeight; renderHeight = outputHeight; } if (fixHeight || !bars) { outputWidth = renderWidth; } if (fixWidth || !bars) { outputHeight = renderHeight; } } } else { if (allowUpscaling) { renderWidth = outputWidth; renderHeight = outputHeight; } else { renderWidth = (inputWidth > outputWidth) ? outputWidth : inputWidth; renderHeight = (inputHeight > outputHeight) ? outputHeight : inputHeight; } } // Center the image. renderLeft = (outputWidth / 2) - (renderWidth / 2); renderTop = (outputHeight / 2) - (renderHeight / 2); outputImage = new Bitmap((int)Math.Round(outputWidth), (int)Math.Round(outputHeight), PixelFormat.Format32bppArgb); using (Graphics graphics = Graphics.FromImage(outputImage)) { graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.High; if (!keepTransparency) { graphics.FillRectangle(backgroundBrush, new Rectangle(0, 0, outputImage.Width, outputImage.Height)); if (bars) { DrawAspectCompensationBars(barBrush, outputWidth, outputHeight, renderLeft, renderTop, renderWidth, renderHeight, graphics); } } graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.DrawImage(image, renderLeft, renderTop, renderWidth, renderHeight); } return outputImage; }
/// <summary> /// Creates a high quality resized version of the provided image /// </summary> /// <param name="original">The original image</param> /// <param name="newWidth">The width of the new image</param> /// <param name="newHeight">The height of the new image</param> /// <param name="resizeMode">Resize mode (defines stretching)</param> /// <param name="padding">Padding around the new image (can be - and often is - negative)</param> /// <param name="backgroundColor">Background color for areas not overlapped by the original image (due to stretch or padding)</param> /// <returns>The image in its new size</returns> public static Image Resize(this Image original, int newWidth, int newHeight, ImageResizeMode resizeMode, int padding, Color backgroundColor) { return(ImageHelper.ResizeImage(original, newWidth, newHeight, resizeMode, padding, backgroundColor)); }
internal static Image Resize(string image, int width, int height, ImageResizeMode resizeMode) { Image i = Image.FromFile(image); return Resize(i, width, height, resizeMode); }
internal static Image Resize(Image image, int width, int height, ImageResizeMode resizeMode) { int sourceWidth = image.Width; int sourceHeight = image.Height; int targetWidth = width; int targetHeight = height; float ratio; float ratioWidth = (targetWidth / (float)sourceWidth); float ratioHeight = (targetHeight / (float)sourceHeight); if (ratioHeight < ratioWidth) ratio = ratioHeight; else ratio = ratioWidth; Bitmap newImage = null; switch (resizeMode) { case ImageResizeMode.Normal: { int destWidth = (int)(sourceWidth * ratio); int destHeight = (int)(sourceHeight * ratio); newImage = new Bitmap(destWidth, destHeight); using (Graphics graphics = Graphics.FromImage(newImage)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(image, 0, 0, destWidth, destHeight); } break; } case ImageResizeMode.Crop: { ratio = ratioHeight > ratioWidth ? ratioHeight : ratioWidth; int destWidth = (int)(sourceWidth * ratio); int destHeight = (int)(sourceHeight * ratio); newImage = new Bitmap(targetWidth, targetHeight); int startX = 0; int startY = 0; if (destWidth > targetWidth) startX = 0 - ((destWidth - targetWidth) / 2); if (destHeight > targetHeight) startY = 0 - ((destHeight - targetHeight) / 2); using (Graphics graphics = Graphics.FromImage(newImage)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(image, startX, startY, destWidth, destHeight); } break; } case ImageResizeMode.Stretch: { newImage = new Bitmap(targetWidth, targetHeight); using (Graphics graphics = Graphics.FromImage(newImage)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(image, 0, 0, targetWidth, targetHeight); } break; } case ImageResizeMode.Fill: { newImage = new Bitmap(targetWidth, targetHeight); int destWidth = (int)(sourceWidth * ratio); int destHeight = (int)(sourceHeight * ratio); int startX = 0; int startY = 0; if (destWidth < targetWidth) startX = 0 + ((targetWidth - destWidth) / 2); if (destHeight < targetHeight) startY = 0 + ((targetHeight - destHeight) / 2); using (Graphics graphics = Graphics.FromImage(newImage)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(image, startX, startY, destWidth, destHeight); } break; } } return newImage; }
/// <summary>Returns the path to an image handler that resizes the given image to the appropriate size.</summary> /// <param name="imageUrl">The image to resize.</param> /// <param name="width">The maximum width.</param> /// <param name="height">The maximum height.</param> /// <param name="mode">How to fit the image</param> /// <returns>The path to a handler that performs resizing of the image.</returns> public static string GetResizedImageUrl(string imageUrl, double width, double height, ImageResizeMode mode) { string fileExtension = VirtualPathUtility.GetExtension(Url.PathPart(imageUrl)); bool isAlreadyImageHandler = string.Equals(fileExtension, ".ashx", StringComparison.OrdinalIgnoreCase); if (isAlreadyImageHandler) { return(Url.ToAbsolute(imageUrl)); } Url url = ImageHandlerUrl.SetQueryParameter("img", N2.Context.Current.ManagementPaths.ResolveResourceUrl(imageUrl)); if (width > 0) { url = url.SetQueryParameter("w", (int)width); } if (height > 0) { url = url.SetQueryParameter("h", (int)height); } url = url.AppendQuery("m", mode.ToString()); return(url); }
public DerivedMediaResourceFile MakeDerivedMediaResourceFile( string uri, int width, int height, List<ImageCreationTask> imageCreationTasks = null, string storedRepresentation = null, ImageResizeMode? imageResizeMode = null, string mimeType = null) { var file = new DerivedMediaResourceFile() { Uri = uri, Height = height, Width = width }; if (imageCreationTasks != null) { imageCreationTasks.Add(new ImageCreationTask { File = file, StoredRepresentation = storedRepresentation, DetermineBestOrientation = false, ImageResizeMode = imageResizeMode, MimeType = mimeType }); } return file; }
private bool Resize(string physicalImagePath, double maxWidth, double maxHeight, ImageResizeMode mode, Stream outputStream) { if (physicalImagePath == null) { throw new ArgumentNullException("imagePath"); } if (!File.Exists(physicalImagePath)) { return(false); } using (Bitmap original = new Bitmap(physicalImagePath)) { Resize(original, new ImageResizeParameters(maxWidth, maxHeight, mode), outputStream); return(true); } }
/// <summary> /// Creates a high quality resized version of the provided image /// </summary> /// <param name="original">The original image</param> /// <param name="newWidth">The width of the new image</param> /// <param name="newHeight">The height of the new image</param> /// <param name="resizeMode">Resize mode (defines stretching)</param> /// <returns>The image in its new size</returns> public static Image ResizeImage(Image original, int newWidth, int newHeight, ImageResizeMode resizeMode) { return(ResizeImage(original, newWidth, newHeight, resizeMode, 0, Color.Transparent)); }
/// <summary> /// Creates a high quality resized version of the provided image /// </summary> /// <param name="original">The original image</param> /// <param name="newWidth">The width of the new image</param> /// <param name="newHeight">The height of the new image</param> /// <param name="resizeMode">Resize mode (defines stretching)</param> /// <returns>The image in its new size</returns> public static Image Resize(this Image original, int newWidth, int newHeight, ImageResizeMode resizeMode) { return(ImageHelper.ResizeImage(original, newWidth, newHeight, resizeMode)); }
public virtual byte[] GetResizedBytes(Stream imageStream, string extension, double maxWidth, double maxHeight, ImageResizeMode mode) { return(GetResizedBytes(imageStream, new ImageResizeParameters(maxWidth, maxHeight, mode))); }
/// <summary> /// Resizes the specified image. /// </summary> /// <param name="image">The input image.</param> /// <param name="width">The output image width.</param> /// <param name="height">The output image height.</param> /// <param name="resizeMode">The <see cref="ImageResizeMode"/>.</param> /// <param name="keepTransparency">A value indicating whether to keep transparency information from the source image.</param> /// <returns>The resized <see cref="Bitmap"/>.</returns> public static Bitmap ResizeImage(Image image, int width, int height, ImageResizeMode resizeMode = ImageResizeMode.Default, bool keepTransparency = true) { return ResizeImage(image, width, height, resizeMode, keepTransparency, Color.White, Color.White); }
/// <summary> /// Creates a high quality resized version of the provided image /// </summary> /// <param name="original">The original image</param> /// <param name="newWidth">The width of the new image</param> /// <param name="newHeight">The height of the new image</param> /// <param name="resizeMode">Resize mode (defines stretching)</param> /// <returns>The image in its new size</returns> public static Image Resize(this Image original, int newWidth, int newHeight, ImageResizeMode resizeMode) { return ImageHelper.ResizeImage(original, newWidth, newHeight, resizeMode); }
public static void CreateThumbnail(string Source, string Destination, int MaxWidth, int MaxHeight, ImageResizeMode Resize = ImageResizeMode.Trim) { using (Image img = Image.FromFile(Source)) { using (Image thumb = CreateThumbnail(img, MaxWidth, MaxHeight, Resize)) { thumb.Save(Destination); } } }
public virtual bool Resize(Stream inputStream, string extension, double maxWidth, double maxHeight, ImageResizeMode mode, Stream outputStream) { using (Bitmap original = new Bitmap(inputStream)) { //if (original.Width < maxWidth && original.Height < maxHeight) //{ // TransferBetweenStreams(inputStream, outputStream); // return true; //} Resize(extension, original, maxWidth, maxHeight, mode, outputStream); return(true); } }
public virtual bool Resize(Stream inputStream, string extension, double maxWidth, double maxHeight, ImageResizeMode mode, Stream outputStream) { return(Resize(inputStream, new ImageResizeParameters(maxWidth, maxHeight, mode), outputStream)); }
/// <summary> /// Initializes a new instance of the ImageOptions class. /// </summary> /// <param name="width">An optional width for the image.</param> /// <param name="height">An optional height for the image.</param> /// <param name="resizeMode">Defines how the image should be resized.</param> public ImageOptions(int?width, int?height, ImageResizeMode resizeMode) { this.Width = width; this.Height = height; this.ResizeMode = resizeMode; }
/// <summary> /// Creates a high quality resized version of the provided image /// </summary> /// <param name="original">The original image</param> /// <param name="newWidth">The width of the new image</param> /// <param name="newHeight">The height of the new image</param> /// <param name="resizeMode">Resize mode (defines stretching)</param> /// <param name="padding">Padding around the new image (can be - and often is - negative)</param> /// <param name="backgroundColor">Background color for areas not overlapped by the original image (due to stretch or padding)</param> /// <returns>The image in its new size</returns> public static Image Resize(this Image original, int newWidth, int newHeight, ImageResizeMode resizeMode, int padding, Color backgroundColor) { return ImageHelper.ResizeImage(original, newWidth, newHeight, resizeMode, padding, backgroundColor); }
public ImageHttpPostedFileBase(HttpPostedFileBase file, Size imageThumbnailSize, int ImageQuality, ImageResizeMode imageResizeMode) : this(file.InputStream, file.ContentType, file.FileName, imageThumbnailSize, ImageQuality, imageResizeMode) { }
public static Image ResizeImage(Image imgToResize, ImageResizeMode resizeMode = ImageResizeMode.OnMinSide, int containerWidth = DEFAULT_CONTAINER_WIDTH, int containerHeight = DEFAULT_CONTAINER_HEIGHT) { Size imgSize = GetNewImageSize(imgToResize.Width, imgToResize.Height, resizeMode, containerWidth, containerHeight); return((Image)(new Bitmap(imgToResize, imgSize))); }
private void Resize(string extension, Bitmap original, double maxWidth, double maxHeight, ImageResizeMode mode, Stream output) { Bitmap resized; if (mode == ImageResizeMode.Fit) { double resizeRation = GetResizeRatio(original, maxWidth, maxHeight); int newWidth = (int)Math.Round(original.Width * resizeRation); int newHeight = (int)Math.Round(original.Height * resizeRation); resized = new Bitmap(newWidth, newHeight, original.PixelFormat); } else resized = new Bitmap((int)maxWidth, (int)maxHeight, original.PixelFormat); resized.SetResolution(original.HorizontalResolution, original.VerticalResolution); Graphics g = CreateGraphics(original, ref resized, extension); using (g) { g.PageUnit = GraphicsUnit.Pixel; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.CompositingMode = CompositingMode.SourceCopy; g.CompositingQuality = CompositingQuality.HighQuality; using (ImageAttributes attr = new ImageAttributes()) { attr.SetWrapMode(WrapMode.TileFlipXY); Rectangle destinationFrame = mode == ImageResizeMode.Fill ? GetFillDestinationRectangle(original.Size, resized.Size) : new Rectangle(Point.Empty, resized.Size); g.DrawImage(original, destinationFrame, 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attr); } resized.Save(output, original.RawFormat); } }
private bool Resize(string physicalImagePath, double maxWidth, double maxHeight, ImageResizeMode mode, Stream outputStream) { if (physicalImagePath == null) { throw new ArgumentNullException("imagePath"); } if (!File.Exists(physicalImagePath)) { return(false); } using (Bitmap original = new Bitmap(physicalImagePath)) { //if (original.Width < maxWidth && original.Height < maxHeight) //{ // using (var fs = File.OpenRead(physicalImagePath)) // { // TransferBetweenStreams(fs, outputStream); // } // return true; //} Resize(Path.GetExtension(physicalImagePath), original, maxWidth, maxHeight, mode, outputStream); return(true); } }
public virtual bool Resize(Stream inputStream, string extension, double maxWidth, double maxHeight, ImageResizeMode mode, Stream outputStream) { return Resize(inputStream, new ImageResizeParameters(maxWidth, maxHeight, mode), outputStream); }
public virtual byte[] GetResizedBytes(Stream imageStream, string extension, double maxWidth, double maxHeight, ImageResizeMode mode) { using (Bitmap original = new Bitmap(imageStream)) { var ms = new MemoryStream(); Resize(extension, original, maxWidth, maxHeight, mode, ms); return(ms.GetBuffer()); } }
/// <summary> /// Resize an image to new width and height /// </summary> /// <param name="img">The image to be resized</param> /// <param name="ImageResizeMode">The mode to use when resizing the image</param> /// <param name="bounds">The new image width and height</param> /// <returns>The resized image</returns> public static Image ResizeImage(this Image img, ImageResizeMode mode, Size bounds, Color baseColor) { return(ResizeImage(img, mode, bounds, baseColor, InterpolationMode.High, SmoothingMode.Default)); }
public virtual byte[] GetResizedBytes(Stream imageStream, string extension, double maxWidth, double maxHeight, ImageResizeMode mode) { return GetResizedBytes(imageStream, new ImageResizeParameters(maxWidth, maxHeight, mode)); }
/// <summary> /// Resize the image /// </summary> /// <param name="args"></param> /// <returns></returns> private dynamic ResizeImage(string path, int w, int h, ImageResizeMode mode, string ext = null) { path = Path.Combine(this.RootPath, path.StartsWith("/") ? path.Substring(1) : path); if (File.Exists(path) == false) { return(404); } if (_Supported.Any(fileExt => path.ToLowerInvariant().EndsWith($".{fileExt}")) == false) { return(400); } var libraryMode = ResizeMode.Crop; switch (mode) { case ImageResizeMode.Fill: libraryMode = ImageProcessor.Imaging.ResizeMode.Crop; break; case ImageResizeMode.FitWidth: libraryMode = ImageProcessor.Imaging.ResizeMode.Max; break; case ImageResizeMode.Fit: libraryMode = ImageProcessor.Imaging.ResizeMode.Max; break; case ImageResizeMode.FitWithBg: libraryMode = ImageProcessor.Imaging.ResizeMode.Pad; break; default: break; } var size = new Size(w, h); var response = new Response(); var resultMS = new MemoryStream(); using (var ms = new MemoryStream(File.ReadAllBytes(path))) using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false)) { var result = imageFactory.Load(ms) .Resize(new ResizeLayer(size, libraryMode)); if (ext == "webp" || this.Request.Headers.Accept.Any(t => t.Item1.Contains("/webp"))) { result = result.Format(new WebPFormat() { Quality = 80 }); } response.ContentType = result.CurrentImageFormat.MimeType; result.Save(resultMS); } response.Contents = (s) => { resultMS.CopyTo(s); }; return(response .WithHeader("Cache-Control", "public, max-age=3600")); }
/// <summary> /// Creates a high quality resized version of the provided image /// </summary> /// <param name="original">The original image</param> /// <param name="newWidth">The width of the new image</param> /// <param name="newHeight">The height of the new image</param> /// <param name="resizeMode">Resize mode (defines stretching)</param> /// <param name="padding">Padding around the new image (can be - and often is - negative)</param> /// <param name="backgroundColor">Background color for areas not overlapped by the original image (due to stretch or padding)</param> /// <returns>The image in its new size</returns> public static Image ResizeImage(Image original, int newWidth, int newHeight, ImageResizeMode resizeMode, int padding, Color backgroundColor) { var bmp = new Bitmap(newWidth, newHeight); var g = Graphics.FromImage(bmp); g.CompositingQuality = CompositingQuality.HighQuality; g.InterpolationMode = InterpolationMode.High; g.SmoothingMode = SmoothingMode.HighQuality; g.Clear(backgroundColor); // This is the area actually used by the resized image int targetWidth = newWidth - (padding * 2); int targetHeight = newHeight - (padding * 2); var renderRect = new Rectangle(0, 0, newWidth, newHeight); switch (resizeMode) { case ImageResizeMode.Stretch: renderRect = new Rectangle((int)((newWidth - targetWidth) / 2), (int)((newHeight - targetHeight) / 2), targetWidth, targetHeight); break; case ImageResizeMode.StretchToFillKeepProportions: decimal verticalFactor = (decimal)targetHeight / (decimal)original.Height; decimal horizontalFactor = (decimal)targetWidth / (decimal)original.Width; var factor = Math.Min(verticalFactor, horizontalFactor); int renderHeight = (int)(original.Height * factor); int renderWidth = (int)(original.Width * factor); renderRect = new Rectangle((int)((newWidth - renderWidth) / 2), (int)((newHeight - renderHeight) / 2), renderWidth, renderHeight); break; case ImageResizeMode.StretchToNearestEdge: decimal verticalFactor2 = (decimal)targetHeight / (decimal)original.Height; decimal horizontalFactor2 = (decimal)targetWidth / (decimal)original.Width; var factor2 = Math.Max(verticalFactor2, horizontalFactor2); int renderHeight2 = (int)(original.Height * factor2); int renderWidth2 = (int)(original.Width * factor2); renderRect = new Rectangle((int)((newWidth - renderWidth2) / 2), (int)((newHeight - renderHeight2) / 2), renderWidth2, renderHeight2); break; } g.DrawImage(original, renderRect); return bmp; }
private bool Resize(string physicalImagePath, double maxWidth, double maxHeight, ImageResizeMode mode, Stream outputStream) { if (physicalImagePath == null) throw new ArgumentNullException("imagePath"); if (!File.Exists(physicalImagePath)) return false; using (Bitmap original = new Bitmap(physicalImagePath)) { Resize(original, new ImageResizeParameters(maxWidth, maxHeight, mode), outputStream); return true; } }