编辑
2025-09-29
C#
00

目录

摘要
正文
使用System.Drawing命名空间
加载图像
生成缩略图
保存缩略图
按比例微缩
总结

摘要

在图像处理中,生成缩略图是一项常见的任务。缩略图是原始图像的小尺寸版本,通常用于在网页、移动应用程序等场景中显示图像的预览或缩略图。本文将介绍如何使用C#来实现生成缩略图的功能,并介绍常用的属性和方法。

正文

使用System.Drawing命名空间

在C#中,我们可以使用System.Drawing命名空间中的类来进行图像处理。这个命名空间提供了许多用于处理图像的类和方法,包括生成缩略图的功能。

首先,我们需要在项目中引用System.Drawing命名空间。在Visual Studio中,右键点击项目,选择“添加” -> “引用”,然后在“程序集”中找到并选中System.Drawing,点击“确定”按钮以添加引用。

加载图像

在生成缩略图之前,我们需要加载原始图像。可以使用Image类的FromFile方法来从文件中加载图像,或者使用FromStream方法从流中加载图像。

C#
// 从文件加载图像 Image originalImage = Image.FromFile("D:\\BaiduSyncdisk\\11Test\\promo.png");
C#
// 从流加载图像 using (FileStream stream = new FileStream("path/to/image.jpg", FileMode.Open)) { Image newImage = Image.FromStream(stream); }

生成缩略图

一旦我们加载了原始图像,就可以使用Image.GetThumbnailImage方法来生成缩略图。这个方法接受缩略图的宽度和高度作为参数,并返回一个新的Image对象,表示生成的缩略图。

C#
int thumbnailWidth = 200; int thumbnailHeight = 200; Image thumbnailImage = originalImage.GetThumbnailImage(thumbnailWidth, thumbnailHeight, null, IntPtr.Zero);

保存缩略图

生成缩略图后,我们可以将其保存到文件或流中。可以使用Image.Save方法来保存图像。

C#
static void Main() { // 从文件加载图像 Image originalImage = Image.FromFile("D:\\BaiduSyncdisk\\11Test\\promo.png"); int thumbnailWidth = 200; int thumbnailHeight = 200; Image thumbnailImage = originalImage.GetThumbnailImage (thumbnailWidth, thumbnailHeight, null, IntPtr.Zero); //保存图 thumbnailImage.Save("D:\\BaiduSyncdisk\\11Test\\promo1.png"); }

image.png

按比例微缩

C#
public class ThumbnailGenerator { public void GenerateThumbnail(string imagePath, string thumbnailPath, int thumbnailWidth, int thumbnailHeight, bool preserveAspectRatio = true) { using (Image originalImage = Image.FromFile(imagePath)) { int width; int height; if (preserveAspectRatio) { // 计算缩放比例 float widthRatio = (float)thumbnailWidth / originalImage.Width; float heightRatio = (float)thumbnailHeight / originalImage.Height; float ratio = Math.Min(widthRatio, heightRatio); // 计算缩略图的实际宽度和高度 width = (int)(originalImage.Width * ratio); height = (int)(originalImage.Height * ratio); } else { width = thumbnailWidth; height = thumbnailHeight; } // 生成缩略图 using (Image thumbnailImage = originalImage.GetThumbnailImage(width, height, null, IntPtr.Zero)) { thumbnailImage.Save(thumbnailPath, ImageFormat.Jpeg);//Png 透明 } } } }
C#
ThumbnailGenerator thumbnailGenerator = new ThumbnailGenerator(); thumbnailGenerator.GenerateThumbnail("D:\\BaiduSyncdisk\\11Test\\promo.png", "D:\\BaiduSyncdisk\\11Test\\promo3.png", 200, 200); pictureBox2.Image = Image.FromFile("D:\\BaiduSyncdisk\\11Test\\promo3.png");

image.png

这个通用的ThumbnailGenerator类具有以下特点:

  • 可以指定要生成缩略图的图像路径、缩略图保存路径、缩略图的宽度和高度。
  • 可以选择保持原始图像的纵横比或不保持纵横比。
  • 使用preserveAspectRatio参数来控制是否保持纵横比,默认为true
  • 生成的缩略图保存为JPEG格式。

总结

通过使用System.Drawing命名空间中的类和方法,我们可以方便地实现图像缩略图的生成。关键步骤包括加载图像、调用GetThumbnailImage方法生成缩略图,并使用Save方法保存缩略图到文件或流中。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!