在网站建设中,关于图片是必不可少的,后台管理中往往需要上传图片,大的图片在网络中传输速率很慢,很不理想,因此解决办法是,用户上传图片时候,保存一个图片的缩略图,在网页显示用缩略图,用户下载,使用原图,下面是通过搜索资料,整理的c#关于保存图片缩略图的方法,用户只需要传入适当参数,调用此方法就可以生成缩略图。

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.IO;publicpartialclassupload:System.Web.UI.Page{protectedvoidPage_Load(objectsender,EventArgse){}}///<summary>///图片等比缩放///</summary>///<paramname="postedfile">原图地址加名称</param>///<paramname="savepath">缩略图存放地址</param>///<paramname="smallname">缩略图名称</param>///<paramname="targetwidth">指定的最大宽度</param>///<paramname="targetheight">指定的最大高度</param>publicstaticvoidzoomauto(stringinitpath,stringsavepath,stringsmallname,doubletargetwidth,doubletargetheight){//虚拟路径转绝对路径initpath=System.Web.HttpContext.Current.Server.MapPath(initpath);savepath=System.Web.HttpContext.Current.Server.MapPath(savepath);//创建目录stringdir=Path.GetDirectoryName(savepath);if(!Directory.Exists(dir))Directory.CreateDirectory(dir);//原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)System.Drawing.Imageinitp_w_picpath=System.Drawing.Image.FromFile(initpath);//原图宽高均小于模版,不作处理,直接保存if(initp_w_picpath.Width<=targetwidth&&initp_w_picpath.Height<=targetheight){//保存initp_w_picpath.Save(savepath+smallname,System.Drawing.Imaging.ImageFormat.Jpeg);}else{//缩略图宽、高计算doublenewwidth=initp_w_picpath.Width;doublenewheight=initp_w_picpath.Height;//宽大于高或宽等于高(横图或正方)if(initp_w_picpath.Width>initp_w_picpath.Height||initp_w_picpath.Width==initp_w_picpath.Height){//如果宽大于模版if(initp_w_picpath.Width>targetwidth){//宽按模版,高按比例缩放newwidth=targetwidth;newheight=initp_w_picpath.Height*(targetwidth/initp_w_picpath.Width);}}//高大于宽(竖图)else{//如果高大于模版if(initp_w_picpath.Height>targetheight){//高按模版,宽按比例缩放newheight=targetheight;newwidth=initp_w_picpath.Width*(targetheight/initp_w_picpath.Height);}}//生成新图//新建一个bmp图片System.Drawing.Imagenewp_w_picpath=newSystem.Drawing.Bitmap((int)newwidth,(int)newheight);//新建一个画板System.Drawing.Graphicsnewg=System.Drawing.Graphics.FromImage(newp_w_picpath);//设置质量newg.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;newg.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;//置背景色newg.Clear(System.Drawing.Color.White);//画图newg.DrawImage(initp_w_picpath,newSystem.Drawing.Rectangle(0,0,newp_w_picpath.Width,newp_w_picpath.Height),newSystem.Drawing.Rectangle(0,0,initp_w_picpath.Width,initp_w_picpath.Height),System.Drawing.GraphicsUnit.Pixel);//保存缩略图newp_w_picpath.Save(savepath+smallname,System.Drawing.Imaging.ImageFormat.Jpeg);//释放资源newg.Dispose();newp_w_picpath.Dispose();initp_w_picpath.Dispose();}}}