在C#開發中,經常會遇到爲某張圖片生成縮略圖的需求,本文提供一個能夠生成縮略圖的C#函數,支持將bmp、png、jpg等常見格式的靜態圖片壓縮,生成縮略圖,可以避免png圖片丟失透明度。不過該函數的圖片壓縮方法比較簡單,只能壓縮20M以內的圖片,圖片大於20M將出現內存錯誤,有待改進。
/// <summary>
/// 壓縮圖片並保存,文件名爲compress_+原文件名
/// </summary>
/// <param name="filePath">原圖路徑</param>
/// <returns>縮略圖路徑</returns>
private string GetReducedImage(string filePath)
{
string fileDir = new StringBuilder(AppDomain.CurrentDomain.BaseDirectory).Append(ICTResources.ICTUser.Session.useraccount).Append("\\Image").ToString();
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
string compressName = new StringBuilder(fileDir).Append("\\compress_").Append(Path.GetFileName(filePath)).ToString();
int minSize = 200;
Graphics draw = null;
System.Drawing.Image ResourceImage = System.Drawing.Image.FromFile(filePath);
double percent = 0.4;
int imageWidth = Convert.ToInt32(ResourceImage.Width);
int imageHeight = Convert.ToInt32(ResourceImage.Height);
if (imageWidth > imageHeight)
{
if (imageWidth > minSize)
{
percent = Convert.ToDouble(minSize) / imageWidth;
imageWidth = minSize;
imageHeight = (int)(imageHeight * percent);
}
}
else
{
if (imageHeight > minSize)
{
percent = Convert.ToDouble(minSize) / imageHeight;
imageHeight = minSize;
imageWidth = (int)(imageWidth * percent);
}
}
// 新建一個bmp圖片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(imageWidth, imageHeight);
System.Drawing.Image bitmap2 = new System.Drawing.Bitmap(imageWidth, imageHeight);
// 新建一個畫板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
try
{
// 設置高質量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
// 設置高質量,低速度呈現平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
// 清空畫布並以透明背景色(白色)填充
g.Clear(System.Drawing.Color.White);
//g.Clear(System.Drawing.Color.Transparent);
// 在指定位置並且按指定大小繪製原圖片的指定部分
g.DrawImage(ResourceImage, new System.Drawing.Rectangle(0, 0, imageWidth, imageHeight));
// 用新建立的image對象拷貝bitmap對象 讓g對象可以釋放資源
draw = Graphics.FromImage(bitmap2);
draw.DrawImage(bitmap, 0, 0);
// 設置縮略圖編碼格式
ImageCodecInfo ici = null;
if (Path.GetExtension(filePath).Equals(".png") || Path.GetExtension(filePath).Equals(".PNG"))
{
//ici = this.getImageCoderInfo("image/png");
ici = this.getImageCoderInfo("image/jpeg");
}
else if (Path.GetExtension(filePath).Equals(".gif") || Path.GetExtension(filePath).Equals(".GIF"))
{
ici = this.getImageCoderInfo("image/gif");
}
else
{
ici = this.getImageCoderInfo("image/jpeg");
}
// 設置壓縮率
long ratio = 20L; // 壓縮爲原圖20%的質量
System.Drawing.Imaging.Encoder ecd = System.Drawing.Imaging.Encoder.Quality;
ResourceImage.Dispose();
bitmap.Dispose();
g.Dispose();
draw.Dispose();
// 保存調整在這裏即可
using (EncoderParameters eptS = new EncoderParameters(1))
{
using (EncoderParameter ept = new EncoderParameter(ecd, ratio))
{
eptS.Param[0] = ept;
bitmap2.Save(compressName, ici, eptS);
}
}
}
catch (System.Exception e)
{
compressName = string.Empty;
}
finally
{
if (ResourceImage != null)
{
ResourceImage.Dispose();
}
if (bitmap != null)
{
bitmap.Dispose();
}
if (g != null)
{
g.Dispose();
}
if (bitmap2 != null)
{
bitmap2.Dispose();
}
if (draw != null)
{
draw.Dispose();
}
}
return compressName;
}
/// <summary>
/// 獲取圖片編碼
/// </summary>
/// <param name="coderType">編碼格式:image/png、image/jpeg等</param>
/// <returns></returns>
private ImageCodecInfo getImageCoderInfo(string coderType)
{
ImageCodecInfo[] iciS = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo retIci = null;
foreach (ImageCodecInfo ici in iciS)
{
if (ici.MimeType.Equals(coderType))
{
retIci = ici;
}
}
return retIci;
}