摘要
在圖像處理中,生成縮略圖是一項(xiàng)常見的任務(wù)。縮略圖是原始圖像的小尺寸版本,通常用于在網(wǎng)頁、移動(dòng)應(yīng)用程序等場景中顯示圖像的預(yù)覽或縮略圖。本文將介紹如何使用C#來實(shí)現(xiàn)生成縮略圖的功能,并介紹常用的屬性和方法。
正文
使用System.Drawing命名空間
在C#中,我們可以使用System.Drawing
命名空間中的類來進(jìn)行圖像處理。這個(gè)命名空間提供了許多用于處理圖像的類和方法,包括生成縮略圖的功能。
首先,我們需要在項(xiàng)目中引用System.Drawing
命名空間。在Visual Studio中,右鍵點(diǎn)擊項(xiàng)目,選擇“添加” -> “引用”,然后在“程序集”中找到并選中System.Drawing
,點(diǎn)擊“確定”按鈕以添加引用。
加載圖像
在生成縮略圖之前,我們需要加載原始圖像。可以使用Image
類的FromFile
方法來從文件中加載圖像,或者使用FromStream
方法從流中加載圖像。
// 從文件加載圖像
Image originalImage = Image.FromFile("D:\\BaiduSyncdisk\\11Test\\promo.png");
// 從流加載圖像
using (FileStream stream = new FileStream("path/to/image.jpg", FileMode.Open))
{
Image newImage = Image.FromStream(stream);
}
生成縮略圖
一旦我們加載了原始圖像,就可以使用Image.GetThumbnailImage
方法來生成縮略圖。這個(gè)方法接受縮略圖的寬度和高度作為參數(shù),并返回一個(gè)新的Image
對(duì)象,表示生成的縮略圖。
int thumbnailWidth = 200;
int thumbnailHeight = 200;
Image thumbnailImage = originalImage.GetThumbnailImage(thumbnailWidth, thumbnailHeight, null, IntPtr.Zero);
保存縮略圖
生成縮略圖后,我們可以將其保存到文件或流中。可以使用Image.Save
方法來保存圖像。
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");
}

按比例微縮
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)
{
// 計(jì)算縮放比例
float widthRatio = (float)thumbnailWidth / originalImage.Width;
float heightRatio = (float)thumbnailHeight / originalImage.Height;
float ratio = Math.Min(widthRatio, heightRatio);
// 計(jì)算縮略圖的實(shí)際寬度和高度
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 透明
}
}
}
}
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");

這個(gè)通用的ThumbnailGenerator
類具有以下特點(diǎn):
總結(jié)
通過使用System.Drawing
命名空間中的類和方法,我們可以方便地實(shí)現(xiàn)圖像縮略圖的生成。關(guān)鍵步驟包括加載圖像、調(diào)用GetThumbnailImage
方法生成縮略圖,并使用Save
方法保存縮略圖到文件或流中。
該文章在 2024/8/27 15:21:20 編輯過