/// <summary>
/// 产生缩略图
/// </summary>
/// <param name="original_image_file">源文件</param>
/// <param name="object_width">缩略图宽度</param>
/// <param name="object_height">缩略图高度</param>
public void MakeThumbnail(string original_image_file, string output_fil, int width, int height, int fist)
{
//获取原始图片
System.Drawing.Bitmap originalImage = new Bitmap(original_image_file);//读取源文件
//缩略图画布宽高
int towidth = width;
int toheight = height;
//原始图片写入画布坐标和宽高(用来设置裁减溢出部分)
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
//原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)
int bg_x = 0;
int bg_y = 0;
int bg_w = towidth;
int bg_h = toheight;
//倍数变量
double multiple = 0;
//获取宽长的或是高长与缩略图的倍数
if (originalImage.Width >= originalImage.Height)
multiple = (double)originalImage.Width / (double)width;
else
multiple = (double)originalImage.Height / (double)height;
//上传的图片的宽和高小等于缩略图
if (ow <= width && oh <= height)
{
//缩略图按原始宽高
bg_w = originalImage.Width;
bg_h = originalImage.Height;
//空白部分用背景色填充
bg_x = Convert.ToInt32(((double)towidth - (double)ow) / 2);
bg_y = Convert.ToInt32(((double)toheight - (double)oh) / 2);
}
//上传的图片的宽和高大于缩略图
else
{
//宽高按比例缩放
bg_w = Convert.ToInt32((double)originalImage.Width / multiple);
bg_h = Convert.ToInt32((double)originalImage.Height / multiple);
//空白部分用背景色填充
bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2);
bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2);
}
Bitmap img = new Bitmap(towidth, toheight);
img.SetResolution(180f, 180f);
Graphics gdiobj = Graphics.FromImage(img);
gdiobj.CompositingQuality = CompositingQuality.HighQuality;
gdiobj.SmoothingMode = SmoothingMode.HighQuality;
gdiobj.InterpolationMode = InterpolationMode.HighQualityBicubic;
gdiobj.PixelOffsetMode = PixelOffsetMode.HighQuality;
try
{
gdiobj.FillRectangle(new SolidBrush(Color.White), 0, 0, ow, oh);
Rectangle destrect = new Rectangle(0, 0, width, height);
gdiobj.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
System.Drawing.Imaging.ImageCodecInfo ici = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[0];
if (ici != null)
{
img.Save(output_fil, ici, ep);
}
else
{
img.Save(output_fil, System.Drawing.Imaging.ImageFormat.Jpeg);
}
gdiobj.Dispose();
}
catch { }
finally
{
originalImage.Dispose();
gdiobj.Dispose();
img.Dispose();
}
}
结合网上搜索到的方法然后在自己加以修改 缩略图不失真