使用 GDI+ 在 ASP.NET 中调整图像大小
使用 GDI+ 在 ASP.NET 中调整图像大小。
引言
我的网站托管在 M6.net 上,遇到了内存不足异常。 结果表明,这是由于在几个图像调整大小的方法中使用 Stream
类造成的。 我研究了将其转换为使用 GDI+,这似乎消耗的内存更少。 它还生成高质量的调整大小后的图像。
使用代码
GetEncoder
辅助方法会选择最合适的 JPEG 编码器。 我还将当前的 Server
对象作为静态变量使用,以方便操作。
ResizeImage
方法执行几项操作。 首先,它确定新图像的比例。 然后,它创建一个新的位图对象,最后创建并保存新图像。很简单。
请注意,我在代码中使用 ~/ 相对路径,因此如果您想使用物理路径,则需要进行调整。
#region Using Directives
using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
#endregion Using Directives
public class ImageResizer
{
#region Fields
static HttpServerUtility Server = HttpContext.Current.Server;
#endregion Fields
#region Get Encoder
public static ImageCodecInfo GetEncoder(string mimeType)
{
foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders())
{
if (codec.MimeType == mimeType)
{
return codec;
}
}
return null;
}
#endregion Get Encoder
#region Resize Image
public static void ResizeImage(string originalImageLocation,
int width, int height, string newImageLocation)
{
Image originalImage = Image.FromFile(
Server.MapPath(originalImageLocation.Replace("//", "/")));
ResizeImage(originalImage, width, height, newImageLocation);
}
public static void ResizeImage(Image originalImage,
int width, int height, string newImageLocation)
{
//
// Scale the image depending on whether it is portrait or landscape.
decimal newWidth;
decimal newHeight;
if ((originalImage.Width / width) > (originalImage.Width / height))
{
newWidth = width;
newHeight = (Int32)Math.Ceiling(Convert.ToDecimal((
originalImage.Height * newWidth) / originalImage.Width));
if (newHeight > height)
{
newWidth = newWidth * (height / newHeight);
newHeight = height;
}
}
else
{
newHeight = height;
newWidth = Math.Ceiling(Convert.ToDecimal((
originalImage.Width * newHeight) / originalImage.Height));
if (newWidth > width)
{
newHeight = newHeight * (width / newWidth);
newWidth = width;
}
}
//
// Create the new image as a bitmap
Bitmap newBitmap = new Bitmap(Convert.ToInt32(newWidth),
Convert.ToInt32(newHeight), PixelFormat.Format16bppRgb565);
Graphics g = Graphics.FromImage(newBitmap);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(originalImage, 0, 0, Convert.ToInt32(newWidth),
Convert.ToInt32(newHeight));
//
// Save the image using the appropriate encoder with a quality of 98%
ImageCodecInfo codecEncoder = ImageResizer.GetEncoder("image/jpeg");
int quality = 98;
EncoderParameters encodeParams = new EncoderParameters(1);
EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);
encodeParams.Param[0] = qualityParam;
newBitmap.SetResolution(72, 72);
newBitmap.Save(Server.MapPath(newImageLocation), codecEncoder, encodeParams);
//
// Clean up
g.Dispose();
newBitmap.Dispose();
originalImage.Dispose();
}
#endregion Resize Image
}
希望这对您有所帮助。