代码实例:在ASP.NET中上传图片并生成缩略图

时间:2021-05-02

privatevoidbtnUploadPicture_Click(objectsender,System.EventArgse) { //检查上传文件的格式是否有效 if(this.UploadFile.PostedFile.ContentType.ToLower().IndexOf("image")<0) { Response.Write("上传图片格式无效!"); return; } //生成原图 Byte[]oFileByte=newbyte[this.UploadFile.PostedFile.ContentLength]; System.IO.StreamoStream=this.UploadFile.PostedFile.InputStream; System.Drawing.ImageoImage=System.Drawing.Image.FromStream(oStream); intoWidth=oImage.Width;//原图宽度 intoHeight=oImage.Height;//原图高度 inttWidth=100;//设置缩略图初始宽度 inttHeight=100;//设置缩略图初始高度 //按比例计算出缩略图的宽度和高度 if(oWidth>=oHeight) { tHeight=(int)Math.Floor(Convert.ToDouble(oHeight)*(Convert.ToDouble(tWidth)/Convert.ToDouble(oWidth))); } else { tWidth=(int)Math.Floor(Convert.ToDouble(oWidth)*(Convert.ToDouble(tHeight)/Convert.ToDouble(oHeight))); } //生成缩略原图 BitmaptImage=newBitmap(tWidth,tHeight); Graphicsg=Graphics.FromImage(tImage); g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.High;//设置高质量插值法 g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度 g.Clear(Color.Transparent);//清空画布并以透明背景色填充 g.DrawImage(oImage,newRectangle(0,0,tWidth,tHeight),newRectangle(0,0,oWidth,oHeight),GraphicsUnit.Pixel); stringoFullName=Server.MapPath(".")+"/"+"o"+DateTime.Now.ToShortDateString().Replace("-","")+DateTime.Now.Hour.ToString()+DateTime.Now.Minute.ToString()+DateTime.Now.Second.ToString()+DateTime.Now.Millisecond.ToString()+".jpg";//保存原图的物理路径 stringtFullName=Server.MapPath(".")+"/"+"t"+DateTime.Now.ToShortDateString().Replace("-","")+DateTime.Now.Hour.ToString()+DateTime.Now.Minute.ToString()+DateTime.Now.Second.ToString()+DateTime.Now.Millisecond.ToString()+".jpg";//保存缩略图的物理路径 try { //以JPG格式保存图片 oImage.Save(oFullName,System.Drawing.Imaging.ImageFormat.Jpeg); tImage.Save(tFullName,System.Drawing.Imaging.ImageFormat.Jpeg); } catch(Exceptionex) { throwex; } finally { //释放资源 oImage.Dispose(); g.Dispose(); tImage.Dispose(); } }

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章