使图像缩略图更小
本文关键字:略图 图像 | 更新日期: 2023-09-27 18:18:47
我有图像共享应用程序,用户上传图像,我采取这些图像的缩略图…无论如何,一切都工作得很好,但有时图像缩略图(600 * 800)大小几乎是1 MB,这是非常巨大的,无论如何都有修改图像分辨率或使大小像…100 KB左右。这是我的代码。
Bitmap bmp = new Bitmap(Width, Height);
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, Width, Height);
System.Drawing.Size rs = new System.Drawing.Size();
rs.Height = Height;
rs.Width = Width;
gr.DrawImage(originalImage, new Rectangle(new Point(0, 0), rs), 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel);
string thumbnailPath = string.Concat(pathToSaveIn, thumbnailName);
bmp.Save(thumbnailPath);
gr.Dispose();
图片大小调整代码(乍一看)看起来不错。但是,您将图像保存为位图格式,这是无损的-因此文件的大小很大。
您可能希望使用JPEG来代替缩略图:对于照片等,这提供了良好的压缩。
这可能有帮助:
public void SaveImage(Bitmap image, string filename)
{
long quality = 80L; // adjust as appropriate
var qualityEncoder = Encoder.Quality;
using (var encoderParameter = new EncoderParameter(qualityEncoder, quality))
using (var encoderParams = new EncoderParameters(1))
{
encoderParams.Param[0] = encoderParameter;
var jpegEncoder = GetEncoder(ImageFormat.Jpeg);
image.Save(filename, jpegEncoder, encoderParams);
}
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
return codecs
.Where(codec => codec.FormatID == format.Guid)
.FirstOrDefault();
}
这看起来像。net。Scott Hanselman有一篇很好的博客文章。本质上是对NuGet上的一个包的回顾,它可以帮助完成这个任务。
http://www.hanselman.com/blog/NuGetPackageOfWeek11ImageResizerEnablesCleanClearImageResizingInASPNET.aspx尝试System.Drawing.Image.GetThumbnailImage。