使用 C# .NET 创建缩略图






2.33/5 (2投票s)
使用 C# .NET 创建图像缩略图,在 Web 应用程序中很有用。
引言
本教程将向您展示如何从原始大图像动态生成图像缩略图。
背景
许多 Web 开发人员会通过为图像标签提供属性值来将大图像显示为小图像。 这会降低网页加载速度。 为了获得更好的性能,最佳方法是创建小的缩略图图像,以便在网页上显示小尺寸图像。 但是,对于用户每次上传图像,我们都无法创建缩略图图像,这是一个繁琐的过程。 我计划创建一个方法,该方法将在图像上传时自动创建缩略图并将其保存到单独的路径中。 这是一个轻量级且易于使用的过程。 唯一的要求是在处理数据库时添加一个额外的字段来保存缩略图图像路径。
以下是此技术的特点。
- 良好的质量。
- 所需的缩略图大小。
Using the Code
以下是生成缩略图并将其保存到目标文件夹的方法。
public void GenerateThumbNail(string sourcefile, string destinationfile,int width)
{
System.Drawing.Image image =
System.Drawing.Image.FromFile(Server.MapPath(sourcefile));
int srcWidth = image.Width;
int srcHeight = image.Height;
int thumbWidth = width;
int thumbHeight;
Bitmap bmp;
if (srcHeight > srcWidth)
{
thumbHeight = (srcHeight / srcWidth) * thumbWidth;
bmp = new Bitmap(thumbWidth, thumbHeight);
}
else
{
thumbHeight = thumbWidth;
thumbWidth = (srcWidth / srcHeight) * thumbHeight;
bmp = new Bitmap(thumbWidth, thumbHeight);
}
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;
System.Drawing.Rectangle rectDestination =
new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
bmp.Save(Server.MapPath(destinationfile));
bmp.Dispose();
image.Dispose();
}
在上述方法中,我们传递三个参数,第一个是图像的源位置,第二个是图像的目标位置,第三个参数是宽度。 首先,我们需要包含两个命名空间。
using System.Drawing;
using System.Drawing.Drawing2D;
然后从源文件创建图像实例,如下所示
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(sourcefile));
获取图像的高度和宽度后,使用图像实例,我们需要设置目标缩略图图像的高度和宽度。 创建一个位图实例。 通过使用以下逻辑,我们可以获得目标缩略图的宽度和高度。 将缩略图的宽度和高度设置为位图。
Bitmap bmp;
if (srcHeight > srcWidth)
{
thumbHeight = (srcHeight / srcWidth) * thumbWidth;
bmp = new Bitmap(thumbWidth, thumbHeight);
}
else
{
thumbHeight = thumbWidth;
thumbWidth = (srcWidth / srcHeight) * thumbHeight;
bmp = new Bitmap(thumbWidth, thumbHeight);
}
之后,为了创建高质量的缩略图,使用位图创建一个 Graphics 类实例。 将 SmoothingMode 和 CompositingQuality 设置为 HighQuality,并将 InterpolationMode 设置为 High。 然后使用 Rectangle 类绘制一个具有缩略图高度和宽度的矩形,并使用 DrawImage 类将图像放置在矩形内。 现在位图图像(即缩略图图像)已准备就绪。 现在使用 bmp.save(/*目标位置*/) 方法将缩略图保存到目标位置。
我认为这个例子在网站开发中,用小图像代替加载大尺寸图像,可以帮助网页加载更快。