我有这段代码,用于调整和保存用户发布的文件的大小。
问题是,当我调整到 480px 宽度时,图像质量会下降很多,而且大小(以 kb 为单位)仍然很大。
例如,当我使用 Paint 之类的软件“手动”将同一图像的大小调整为 480px 时,质量仍然与原始图像一样好(从我的眼睛可以看出),并且以 kb 为单位的大小比使用调整大小要小得多这GetThumbNailImage
method.
姆登 说“如果您从嵌入缩略图的图像中请求大缩略图(例如 300 x 300),则缩略图的质量可能会明显下降。缩放主图像可能会更好(而不是缩放嵌入的缩略图)通过调用DrawImage
方法。”,但这似乎适用于 Windows 表单,我需要一个网络应用程序。
那么我应该使用什么代码来执行此操作?
System.IO.Stream st = FileUploadPost.PostedFile.InputStream;
myImage = System.Drawing.Image.FromStream(st);
thumb = myImage.GetThumbnailImage(newWidth, newHeight, null, System.IntPtr.Zero);
thumb.Save(myPath);
这是对我有用的代码。您可以设置新的位图分辨率:
using System.Drawing;
Bitmap img = (Bitmap)Bitmap.FromStream(FileUploadPost.PostedFile.InputStream);
Bitmap newImg = new Bitmap(maxWidth, maxHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
newImg.SetResolution(72, 72);
Graphics newGraphic = Graphics.FromImage(newImg);
newGraphic.Clear(Color.Transparent);
newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newGraphic.DrawImage(img, 0, 0, maxWidth, maxHeight);
System.Drawing.Imaging.ImageFormat format = default(System.Drawing.Imaging.ImageFormat);
string ext = Path.GetExtension(FileUploadPost.PostedFile.FileName);
switch (ext.ToLower())
{
case ".gif":
format = System.Drawing.Imaging.ImageFormat.Gif;
break;
case ".png":
format = System.Drawing.Imaging.ImageFormat.Png;
break;
default:
format = System.Drawing.Imaging.ImageFormat.Jpeg;
break;
}
newImg.Save(myPath, format);
您可以将其包装在全局类的 void 函数中:
public static void UploadImage(HttpPostedFileBase file, int maxWidth, int maxHeight)
{
//paste all the above code in here and replace FileUploadPost.PostedFile with file
}
然后您可以从项目中的任何位置调用它:
ClassName.UploadImage(FileUploadPost.PostedFile, 300, 300);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)