|
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
/**//// <summary>
///
/// **生成高質(zhì)量縮略圖程序**
///
/// File: GenerateThumbnail.cs
///
/// Author: 周振興 (Zxjay 飄遙)
///
/// E-Mail: tda7264@163.com
///
/// Date: 07-04-07
///
/// </summary>
public class GenerateThumbnail
...{
/**//// <summary>
/// 生成縮略圖 靜態(tài)方法
/// </summary>
/// <param name="pathImageFrom"> 源圖的路徑(含文件名及擴展名) </param>
/// <param name="pathImageTo"> 生成的縮略圖所保存的路徑(含文件名及擴展名)
/// 注意:擴展名一定要與生成的縮略圖格式相對應(yīng) </param>
/// <param name="width"> 欲生成的縮略圖 "畫布" 的寬度(像素值) </param>
/// <param name="height"> 欲生成的縮略圖 "畫布" 的高度(像素值) </param>
public static void GenThumbnail(string pathImageFrom,string pathImageTo,int width,int height)
...{
Image imageFrom = null;
try
...{
imageFrom = Image.FromFile(pathImageFrom);
}
catch
...{
//throw;
}
if (imageFrom == null)
...{
return;
}
// 源圖寬度及高度
int imageFromWidth = imageFrom.Width;
int imageFromHeight = imageFrom.Height;
// 生成的縮略圖實際寬度及高度
int bitmapWidth = width;
int bitmapHeight = height;
// 生成的縮略圖在上述"畫布"上的位置
int X = 0;
int Y = 0;
// 根據(jù)源圖及欲生成的縮略圖尺寸,計算縮略圖的實際尺寸及其在"畫布"上的位置
if (bitmapHeight * imageFromWidth > bitmapWidth * imageFromHeight)
...{
bitmapHeight = imageFromHeight * width / imageFromWidth;
Y = (height - bitmapHeight) / 2;
}
else
...{
bitmapWidth = imageFromWidth * height / imageFromHeight;
X = (width - bitmapWidth) / 2;
}
// 創(chuàng)建畫布
Bitmap bmp = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bmp);
// 用白色清空
g.Clear(Color.White);
// 指定高質(zhì)量的雙三次插值法。執(zhí)行預(yù)篩選以確保高質(zhì)量的收縮。此模式可產(chǎn)生質(zhì)量最高的轉(zhuǎn)換圖像。
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// 指定高質(zhì)量、低速度呈現(xiàn)。
g.SmoothingMode = SmoothingMode.HighQuality;
// 在指定位置并且按指定大小繪制指定的 Image 的指定部分。
g.DrawImage(imageFrom, new Rectangle(X, Y, bitmapWidth, bitmapHeight), new Rectangle(0, 0, imageFromWidth, imageFromHeight), GraphicsUnit.Pixel);
try
...{
//經(jīng)測試 .jpg 格式縮略圖大小與質(zhì)量等最優(yōu)
bmp.Save(pathImageTo, ImageFormat.Jpeg);
}
catch
...{
}
finally
...{
//顯示釋放資源
imageFrom.Dispose();
bmp.Dispose();
g.Dispose();
}
}
}
生成的縮略圖大小一定,無剪裁、無變形。
可以測試一下各種圖形格式、圖形質(zhì)量、呈現(xiàn)方式生成的縮略圖的大小和視覺質(zhì)量。
經(jīng)測試:Vista 原默認桌面 .jpg 格式 尺寸:1024*768,
生成原尺寸大小的縮略圖,比較如下:
原圖.jpg格式,223 KB
.jpg 102KB
.png 1816 KB
.gif 228 KB
.tiff 2000KB 以上
…
視覺上 除 .gif 質(zhì)量較差外,其他的與源圖肉眼無法區(qū)別(本人有點近視^-^)
在考慮到專利及通用性等因素,推薦用 .jpg 格式。
AspNet技術(shù):C# 生成高質(zhì)量縮略圖程序―終極算法,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。