ASP.NET中图片显示方法实例
本文实例讲述了ASP.NET中图片的显示方法。分享给大家供大家参考。具体如下:
genimage.ashx:
<%@WebHandlerLanguage="C#"Class="netpix.ImageGenerator"%>
genimage.ashx.cs:
//Copyright(C)2003byGregEnnis //(mailto:greg@ennis.net) // //ThecontentsofthisfilearesubjecttotheArtisticLicense(the"License"). //YoumaynotusethisfileexceptincompliancewiththeLicense. //YoumayobtainacopyoftheLicenseat: //http://www.opensource.org/licenses/artistic-license.html usingSystem; usingSystem.Collections; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Data.SqlClient; usingSystem.Drawing; usingSystem.Web; usingSystem.IO; usingSystem.Configuration; usingSystem.Web.SessionState; usingSystem.Web.UI; usingSystem.Web.UI.WebControls; usingSystem.Web.UI.HtmlControls; namespacenetpix { publicclassImageGenerator:IHttpHandler { publicboolIsReusable {get{returntrue;}} publicvoidProcessRequest(HttpContextContext) { //Gettheimagefilenameandalbumrootpathfromthedatabase //图片浏览次数 intnumviews; //图片数据库中的ID intpicid=Convert.ToInt32(Context.Request["id"]); //图片路径 stringimgpath=npdata.GetPathToPicture(picid,outnumviews); //Writinganimagetooutputstream Context.Response.ContentType="image/jpg"; //'thumbnail'meanswearerequestingathumbnail //显示缩略图 if(Context.Request["thumbnail"]!=null) { //Needtoloadtheimage,resizeit,andstreamtotheclient. //Calculatethescalesoasnottostretchordistorttheimage. Bitmapbmp=newBitmap(imgpath); floatscale=150.0f/System.Math.Max(bmp.Height,bmp.Width); System.Drawing.Imagethumb=bmp.GetThumbnailImage((int)(bmp.Width*scale),(int)(bmp.Height*scale),null,System.IntPtr.Zero); thumb.Save(Context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg); bmp.Dispose(); thumb.Dispose(); } else { //Streamdirectlyfromthefile //Getthestreamandsenditouttheresponse System.IO.FileStreamfs=File.Open(imgpath,FileMode.Open,FileAccess.Read,FileShare.Read); constintbyteLength=8192; byte[]bytes=newbyte[byteLength]; while(fs.Read(bytes,0,byteLength)!=0) { Context.Response.BinaryWrite(bytes); } fs.Close(); //更新数据库浏览次数 npdata.SetNumViews(picid,numviews+1); } } } }
使用方法:
imgCtrl.ImageUrl="genimage.ashx?id="+Request["id"];
希望本文所述对大家的ASP.NET程序设计有所帮助。