public class ThumbnailHelper
{
/// <summary>
/// 生成缩略图(最终图片固定大小,图片按照传入宽度和高度进行缩小,以传入格式进行保存,支持jpg、bmp、gif、png;其他格式默认以jpg格式保存)
/// </summary>
/// /// <param name="sourceImg">原图片(物理路径)</param>
/// <param name="toPath">缩略图存放地址(物理路径,带文件名)</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
public static int MakePic(string sourceImg, string toPath, int pW, int pH)
{
System.Drawing.Image originalImage = null;
System.Drawing.Image bitmap = null;
System.Drawing.Graphics g = null;
try
{
string imgType = sourceImg.Substring(sourceImg.LastIndexOf('.') + 1);
originalImage = System.Drawing.Image.FromFile(sourceImg);
int oW = originalImage.Width;//原始图片宽
int oH = originalImage.Height;//原始图片高
int tW = oW;//最终显示到页面宽
int tH = oH;//最终显示到页面高
//图片宽高赋值要求大小
tW = pW;
tH = pH;
//新建一个bmp图片
bitmap = new System.Drawing.Bitmap(tW, tH);
//新建一个画板
g = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, tW, tH), new System.Drawing.Rectangle(0, 0, oW, oH), System.Drawing.GraphicsUnit.Pixel);
//以原格式格式保存缩略图
if (imgType == "jpg")
{
bitmap.Save(toPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
else if (imgType == "gif")
{
bitmap.Save(toPath, System.Drawing.Imaging.ImageFormat.Gif);
}
else if (imgType == "png")
{
bitmap.Save(toPath, System.Drawing.Imaging.ImageFormat.Png);
}
else if (imgType == "bmp")
{
bitmap.Save(toPath, System.Drawing.Imaging.ImageFormat.Bmp);
}
else
{
bitmap.Save(toPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
return 1;
}
catch
{
return -1;
}
finally
{
if (originalImage != null)
{
originalImage.Dispose();
}
if (bitmap != null)
{
bitmap.Dispose();
}
if (g != null)
{
g.Dispose();
}
}
}
}
C# 生成缩略图
最新推荐文章于 2015-12-13 13:55:57 发布