ASP.NET 生成缩略图片类分享
/// <summary>
/// 生成图片缩略图 指定文件路径生成
/// </summary>
public static void SaveImage(String fullName, string fileName, int w, int h)
{
FileStream fs = new FileStream(fullName, FileMode.Open);
System.Drawing.Image image = System.Drawing.Image.FromStream(fs, true);
fs.Close();
SaveImage(image, fileName, w, h);
}
/// <summary>
/// 生成图片缩略图 指定文件流生成
/// </summary>
public static void SaveImage(Stream fs, string fileName, int w, int h)
{
Image image = System.Drawing.Image.FromStream(fs, true);
SaveImage(image, fileName, w, h);
}
/// <summary>
/// 生成图片缩略图
/// </summary>
public static void SaveImage(System.Drawing.Image image, string fileName, int w, int h, int high = 90)
{
if (w == 0 && h == 0)
{
w = image.Width;
h = image.Height;
}
else if (w > 0 && h > 0)
{
if (image.Width > image.Height)
{
if (image.Width > w)
{
h = (int)(image.Height * ((decimal)w / image.Width));
}
else
{
h = image.Height;
w = image.Width;
}
}
else
{
if (image.Height > h)
{
w = (int)(image.Width * ((decimal)h / image.Height));
}
else
{
h = image.Height;
w = image.Width;
}
}
}
else if (w > 0)
{
if (image.Width > w)
{
h = (int)(image.Height * ((decimal)w / image.Width));
}
else
{
h = image.Height;
w = image.Width;
}
}
else if (h > 0)
{
if (image.Height > h)
{
w = (int)(image.Width * ((decimal)h / image.Height));
}
else
{
h = image.Height;
w = image.Width;
}
}
Bitmap ret = new Bitmap(w, h);
using (Graphics g = Graphics.FromImage(ret))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, w, h);
g.DrawImage(image, 0, 0, w, h);
EncoderParameters parms = new EncoderParameters();
long[] quality = new long[1];
quality[0] = high;
EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
parms.Param[0] = parm;
ImageCodecInfo[] arr = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo ar = null;
for (int x = 0; x < arr.Length; x++)
{
if (arr[x].FormatDescription.Equals("JPEG"))
{
ar = arr[x];
break;
}
}
ret.Save(fileName, ar, parms);
ret.Dispose();
image.Dispose();
}
}
ASP.NET PHP 网站建设,欢迎加QQ群 8197815 ,一起学习交流。
浙公网安备 33010602011771号