C# 图片生成缩略图

时间:2024-08-10 00:03:26

C# 图片生成缩略图方法:

 /// <summary>
/// 生成缩略图
/// </summary>
/// <param name="fileName">原图路径</param>
/// <param name="newFile">缩略图路径</param>
/// <param name="maxHeight">最大高度</param>
/// <param name="maxWidth">最大宽度</param>
public string ThumbnailImage(string fileName, string newFile, int maxHeight, int maxWidth)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(fileName);
System.Drawing.Imaging.ImageFormat thisFormat = img.RawFormat;
//缩略图尺寸
double w = 0.0; //图片的宽
double h = 0.0; //图片的高
double sw = Convert.ToDouble(img.Width);
double sh = Convert.ToDouble(img.Height);
double mw = Convert.ToDouble(maxWidth);
double mh = Convert.ToDouble(maxHeight);
if (sw < mw && sh < mh)
{
w = sw;
h = sh;
}
else if ((sw / sh) > (mw / mh))
{
w = maxWidth;
h = (w * sh) / sw;
}
else
{
h = maxHeight;
w = (h * sw) / sh;
}
Size newSize = new Size(Convert.ToInt32(w), Convert.ToInt32(h));
Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
Graphics g = Graphics.FromImage(outBmp);
//设置画布的描绘质量
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(img, new Rectangle(, , newSize.Width, newSize.Height), , , img.Width, img.Height, GraphicsUnit.Pixel);
g.Dispose();
//以下代码为保存图片时,设置压缩质量
EncoderParameters encoderParams = new EncoderParameters();
long[] quality = new long[];
quality[] = ;
EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
encoderParams.Param[] = encoderParam;
//获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICI = null;
for (int x = ; x < arrayICI.Length;x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICI = arrayICI[x];
//设置JPEG编码
break;
}
}
if (jpegICI != null)
{
Bitmap newbit = new Bitmap(outBmp);
newbit.Save(newFile, jpegICI, encoderParams);
}
else
{
outBmp.Save(newFile,
thisFormat);
}
img.Dispose();
outBmp.Dispose();
return newFile;
}