1.生成缩略图的主要代码
/// <summary>
/// 图片显示成缩略图
/// </summary>
/// <param name="sourcePath" >图片原路径</param>
/// <param name="newPath">生成的缩略图新路径</param>
/// <param name="width">生成的缩略图宽度</param>
/// <param name="height">生成的缩略图高度</param>
public static void MakeThumbnail(string sourcePath, string newPath, int width, int height)
{
sourcePath = System.Web.HttpContext.Current.Server.MapPath(sourcePath);
newPath = System.Web.HttpContext.Current.Server.MapPath(newPath);
System.Drawing.Image ig = System.Drawing.Image.FromFile(sourcePath);
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = ig.Width;
int oh = ig.Height;
if ((double)ig.Width / (double)ig.Height > (double)towidth / (double)toheight)
{
oh = ig.Height;
ow = ig.Height * towidth / toheight;
y = 0;
x = (ig.Width - ow) / 2;
}
else
{
ow = ig.Width;
oh = ig.Width * height / towidth;
x = 0;
y = (ig.Height - oh) / 2;
}
System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(System.Drawing.Color.Transparent);
g.DrawImage(ig, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
try
{
bitmap.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex)
{
throw ex;
}
finally
{
ig.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
2.具体操作流程
1.` protected void Page_Load(object sender, EventArgs e)
{
if (File.Exists(Server.MapPath(“现有图片路径”.ToString())))//判断现有图片路径是否存在
{
S_ImageHelper.MakeThumbnail(“现有图片路径”.ToString(), “新建缩略图路径”, 275, 254);
}
Response.Write("成功");
}`
3。显示成功,则缩略图生成好了,去看看你的新建路径里面是否又该图片吧