所属类别:Asp
文章作者:未知
特别推荐:免费发布信息 承包关键词~~抢爆了!HOT!
ASP.NET动态创建图象 http://www.tongyi.net出处:chinaasp点击:435Level:Beginner/IntermediateOneoftheneatfeaturesthatyoucannowleveragewith.NETistheabilitytoeasilygeneratedynamicimagesfromcode,whichyoucantheneithersavetodiskordirectlystreambacktoabrowserclientwithASP.NET.Thefunctionalitytogenerateimageswith.NETisencapsulatedwithintheSystem.Drawingnamespace.Itprovidesbuilt-insupportforgeneratingimageswithanumeroffileformatsincluding:JPEG,GIF,PNG,TIFF,BMP,PhotoCD,FlashPIX,WMF,EMFandEXIF.Notethattherearenolicenseissuestoworryaboutwithanyofthesefileformats;Microsoftimplementationofeachformatislicensefree(includingforGIFimages).ThegeneralmechanismthroughwhichyougeneratethesegraphicsimagesisbyconstructingaBitMapobjectwhichprovidesanin-memoryrepresentationofyourimage.Youcanthencallits"Save"methodtoeithersaveittodisk,orstreamitouttoany.NEToutputstream.BecauseASP.NETexposesa.NETOutputStreamviatheResponse.OutputStreamproperty.Thismeansyoucanstreamtheimagecontentsdirectlytothebrowserwithouteverhavingtosaveittodisk.Forexample,todothisinVByouwouldwritecodelike:'CreateIn-MemoryBitMapofJPEGDimMyChartEngineasNewChartEngineDimStockBitMapasBitMap=MyChartEngine.DrawChart(600,400,myChartData)'RenderBitMapStreamBackToBrowserStockBitMap.Save(Response.OutputStream,ImageFormat.JPEG)IfyouareusinganASPXpagetodothis,youwillwanttomakesureyousettheappropriateHTTPContentTypeheaderaswell,sothatthebrowserclientdoesn'tinterpretthepage'scontentashtmlbutratherasanimage.YoucandothiseitherviasettingtheResponse.ContentTypepropertythroughcode,orviathenew"ContentType"attributethatyoucansetonthetop-levelpagedirective:<%@PageLanguage="VB"ContentType="image/jpeg"%>NotethattheoutputcachingfeaturesofASP.NETworkforbothtextualcontentaswellasforbinaryoutput.Assuch,ifyouaredynamicallygeneratinganimagefromapage,youcaneasilyleveragetheoutputcachedirectivetoavoidhavingtoregeneratetheimageoneachrequest.Notethatimagegenerationcanbeexpensive,sothisfeatureishighlyrecommended.Forexample,thebelowdirectivecouldbeusedtooutputcachethegeneratedimagefora60secondinterval:<%@PageLanguage="VB"ContentType="image/jpeg"%><%@OutputCacheDuration="60"%>Foracompletesampleofhowtouseimagegeneration,I'veincludedasimplestockchartgenerationsamplebelow.Notethatthestockpricesaren'treal,justwishfulthinkingonmypart.Thesampleusesacustom"ChartEngine"classthathelpsencapsulatethelogicrequiredtobuildupagenericchart.Youshouldbeabletousethishelpercomponenttodoanycustomchartingofyourown,itisdefinitelynotlimitedtojuststockdata.Feelfreetouseanyofthecodehoweveryouwantandlikewithallmyothersamples,feelfreetopostelsewhereaswellastouseforarticles,othersamples,etc).Instructions:Torunthesample,copy/paste/savethebelowfilesintoanIISApplicationVRoot.Thentypethebelowstatementsintoacommandline:mkdirbincsc/t:library/out:bin\chartgen.dllChartEngine.cs/r:System.Web.dll/r:System.Winforms.dll/r:System.Drawing.dll/r:System.dllOncethechartenginehelperutilityiscompiled,hittheStockPicker.aspxpagetorunthesample(notethatthisinturnsetsupatagtopointtotheImageGenerator_VB.aspxpagethatdoestheactualimagegenerationwork).StockPicker.aspx:SubChartBtn_Click(SenderasObject,EasEventArgs)chart.ImageUrl="ImageGenerator_Vb.aspx?"chart.Visible=trueFori=0toStocks.Items.Count-1If(Stocks.Items(i).Selected=true)Thenchart.ImageUrl=chart.ImageUrl&"symbols="&Stocks.Items(i).Value&"&"EndIfNextEndSubScott'sStockPickerMSFTSUNImageGenerator_VB.aspx:<%@PageLanguage="VB"ContentType="image/jpeg"%><%@ImportNamespace="System.Drawing"%><%@ImportNamespace="System.Drawing.Drawing2D"%><%@ImportNamespace="System.Drawing.Imaging"%><%@ImportNamespace="ChartGenerator"%><%@OutputCacheDuration="10"%>FunctionGetStockDetails(SymbolasString)asChartLineDimmyChartLineasnewChartLineif(symbol="msft")thenDimStockValues()asSingle={60,110,120,180,185,190,240,290}myChartLine.Width=5myChartLine.Color=Color.BluemyChartLine.LineStyle=DashStyle.SolidmyChartLine.Title="MicrosoftCorp.(MSFT)"myChartLine.Symbol="MSFT"myChartLine.Values=StockValuesreturnmyChartLineelseif(symbol="sun")thenDimStockValues()asSingle={180,155,125,60,25,15,10,3}myChartLine.Width=5myChartLine.Color=Color.RedmyChartLine.LineStyle=DashStyle.DotmyChartLine.Title="SunCorp.(Sun)"myChartLine.Symbol="Sun"myChartLine.Values=StockValuesreturnmyChartLineendifreturnnothingEndFunctionSubPage_Load(SenderasObject,EasEventArgs)'GenerateChartDataForImage....DimXAxes()asString={"9:00AM","9:30AM","10:00AM","11:00AM","12:00AM","1:00PM","1:30PM"}DimMyChartDataasNewChartDataMyChartData.YTickSize=20MyChartData.YMax=250MyChartData.YMin=0MyChartData.XAxisTitles=XAxesDimSymbols()asString=Request.QueryString.GetValues("symbols")if(NotSymbols=Nothing)thenfori=0toSymbols.Length-1DimstockValueasChartLine=GetStockDetails(symbols(i).ToLower)If(stockValue<>nothing)thenmyChartData.Lines.Add(stockValue)EndifNextendif'CreateIn-MemoryBitMapofJPEGDimMyChartEngineasNewChartEngineDimStockBitMapasBitMap=MyChartEngine.DrawChart(600,400,myChartData)'RenderBitMapStreamBackToClientStockBitMap.Save(Response.OutputStream,ImageFormat.JPEG)EndSubChartEngine.cs:usingSystem.WinForms;usingSystem.Collections;usingSystem.Collections.Bases;usingSystem.Drawing;usingSystem.Drawing.Drawing2D;usingSystem.Drawing.Imaging;usingSystem.ComponentModel;usingSystem;usingSystem.IO;namespaceChartGenerator{//CoreLineDatastructurepublicstructLineData{publicfloat[]LineValues;publicstringLineTitle;publicstringLineSymbol;}//LineDataplusdisplaystyleinformationpublicclassChartLine{privateColorlineColor;privateLineDatalineData;privateDashStylelineStyle;privateintlineWidth;//ConstructorspublicChartLine():base(){}publicChartLine(LineDatalineData):base(){this.lineData=lineData;}//PropertiespublicColorColor{get{returnlineColor;}set{lineColor=value;}}publicDashStyleLineStyle{get{returnlineStyle;}set{lineStyle=value;}}publicstringSymbol{get{returnlineData.LineSymbol;}set{lineData.LineSymbol=value;}}publicstringTitle{get{returnlineData.LineTitle;}set{lineData.LineTitle=value;}}publicfloat[]Values{get{returnlineData.LineValues;}set{lineData.LineValues=value;}}publicintWidth{get{returnlineWidth;}set{lineWidth=value;}}//MethodspublicvoidSetLineData(LineDatalineData){this.lineData=lineData;}}//ChartDatastructurepublicclassChartData{privatefloatyTickSize;privatefloatyMax;privatefloatyMin;privatestring[]xAxisTitles;privateChartLineListlines=newChartLineList();privateColorgridColor=Color.Blue;privateboolshowHGridLines=true;privateboolshowVGridLines=true;//PropertiespublicfloatYTickSize{get{returnyTickSize;}set{yTickSize=value;}}publicfloatYMax{get{returnyMax;}set{yMax=value;}}publicfloatYMin{get{returnyMin;}set{yMin=value;}}publicstring[]XAxisTitles{get{returnxAxisTitles;}set{xAxisTitles=value;}}publicChartLineListLines{get{returnlines;}set{lines=value;}}publicColorGridColor{get{returngridColor;}set{gridColor=value;}}publicboolShowHGridLines{get{returnshowHGridLines;}set{showHGridLines=value;}}publicboolShowVGridLines{get{returnshowVGridLines;}set{showVGridLines=value;}}//CollectionofChartLinespublicclassChartLineList:TypedCollectionBase{publicChartLinethis[intindex]{get{return(ChartLine)(List[index]);}set{List[index]=value;}}publicintAdd(ChartLinevalue){returnList.Add(value);}publicvoidInsert(intindex,ChartLinevalue){List.Insert(index,value);}publicintIndexOf(ChartLinevalue){returnList.IndexOf(value);}publicboolContains(ChartLinevalue){returnList.Contains(value);}publicvoidRemove(ChartLinevalue){List.Remove(value);}publicvoidCopyTo(ChartLine[]array,intindex){List.CopyTo(array,index);}}}//ChartingEngine-drawsachartbasedonthegivenChartDatapublicclassChartEngine{privateChartDatachartData;privatefloatleft;privatefloatright;privatefloattop;privatefloatbottom;privatefloattickCount;privatefloatyCount;privatefloathspacing;privatefloatvspacing;privateGraphicsg;privateRectangler;privateColorbackColor;privateColorforeColor;privateFontbaseFont;privateFontlegendFont;privateRectangleFlegendRect;publicChartEngine(){}publicBitmapDrawChart(intwidth,intheight,ChartDatachartData){BitmapnewBitmap=newBitmap(width,height,PixelFormat.Format32bppARGB);Graphicsg=Graphics.FromImage(newBitmap);Rectangler=newRectangle(0,0,width,height);ColormyForeColor=Color.Black;ColormyBackColor=Color.White;FontmyFont=newFont("Arial",10);this.DrawChart(g,r,myBackColor,myForeColor,myFont,chartData);returnnewBitmap;}publicvoidDrawChart(Graphicsg,Rectangler,ColorbackColor,ColorforeColor,FontbaseFont,ChartDatachartData){this.chartData=chartData;this.g=g;this.r=r;this.backColor=backColor;this.foreColor=foreColor;this.baseFont=baseFont;this.legendFont=newFont(baseFont.FontFamily,(baseFont.Size*2/3),baseFont.StyleFontStyle.Bold);g.SmoothingMode=SmoothingMode.AntiAlias;CalculateChartDimensions();DrawBackground();InternalDrawChart();}privatevoidCalculateChartDimensions(){right=r.Width-5;top=5*baseFont.Size;bottom=r.Height-baseFont.Size*2;tickCount=chartData.YMin;yCount=(chartData.YMax-chartData.YMin)/chartData.YTickSize;hspacing=(bottom-top)/yCount;vspacing=(right)/chartData.XAxisTitles.Length;//Leftdependsonwidthoftext-forsimplicitiessakeassumethatlargestyvalueisthebiggest//TakeintoaccountthefirstXAxistitlefloatmaxYTextSize=g.MeasureString(chartData.YMax.ToString(),baseFont).Width;floatfirstXTitle=g.MeasureString(chartData.XAxisTitles[0],baseFont).Width;left=(maxYTextSize>firstXTitle)?maxYTextSize:firstXTitle;left=r.X+left+5;//CalculatesizeoflegendboxfloatmaxLegendWidth=0;floatmaxLegendHeight=0;//Workoutsizeofbiggestlegendforeach(ChartLineclinchartData.Lines){floatcurrentWidth=g.MeasureString(cl.Title,legendFont).Width;floatcurrentHeight=g.MeasureString(cl.Title,legendFont).Height;maxLegendWidth=(maxLegendWidth>currentWidth)?maxLegendWidth:currentWidth;maxLegendHeight=(maxLegendHeight>currentHeight)?maxLegendHeight:currentHeight;}legendRect=newRectangleF(r.X+2,r.Y+2,maxLegendWidth+25+5,((maxLegendHeight+2)*chartData.Lines.Count)+3);}privatevoidDrawBackground(){LinearGradientBrushb=newLinearGradientBrush(r,Color.SteelBlue,backColor,LinearGradientMode.Horizontal);g.FillRectangle(b,r);b.Dispose();}privatevoidInternalDrawChart(){DrawGrid();foreach(ChartLineclinchartData.Lines){DrawLine(cl);}DrawLegend();//DrawtimeonchartstringtimeString="Generated:"+DateTime.Now.ToLongTimeString();SizeFtextsize=g.MeasureString(timeString,baseFont);g.DrawString(timeString,baseFont,newSolidBrush(foreColor),r.Width-textsize.Width-5,textsize.Height*2/3);}privatevoidDrawGrid(){PengridPen=newPen(chartData.GridColor);//Vertical-includetickdesc'sif(chartData.ShowVGridLines){for(inti=0;(vspacing*i)<right;i++){floatx=left+(vspacing*i);stringdesc=chartData.XAxisTitles[i];g.DrawLine(gridPen,x,top,x,bottom+(baseFont.Size*1/3));SizeFtextsize=g.MeasureString(desc,baseFont);g.DrawString(desc,baseFont,newSolidBrush(chartData.GridColor),x-(textsize.Width/2),bottom+(baseFont.Size*2/3));}}//Horizontalif(chartData.ShowHGridLines){for(floati=bottom;i>top;i-=hspacing){stringdesc=tickCount.ToString();tickCount+=chartData.YTickSize;g.DrawLine(gridPen,right,i,left-3,i);SizeFtextsize=g.MeasureString(desc,baseFont);g.DrawString(desc,baseFont,newSolidBrush(chartData.GridColor),left-textsize.Width-3,i-(textsize.Height/2));}}}privatevoidDrawLine(ChartLinechartLine){PenlinePen=newPen(chartLine.Color);linePen.StartCap=LineCap.Round;linePen.EndCap=LineCap.Round;linePen.Width=chartLine.Width;linePen.DashStyle=chartLine.LineStyle;PointF[]Values=newPointF[chartLine.Values.Length];floatscale=hspacing/chartData.YTickSize;for(inti=0;i<chartLine.Values.Length;i++){floatx=left+vspacing*i;Values[i]=newPointF(x,bottom-chartLine.Values[i]*scale);}g.DrawLines(linePen,Values);}privatevoidDrawLegend(){//DrawLegendBoxControlPaint.DrawBorder(g,(Rectangle)legendRect,SystemColors.WindowFrame,ButtonBorderStyle.Solid);LinearGradientBrushb=newLinearGradientBrush(legendRect,backColor,Color.SteelBlue,LinearGradientMode.Horizontal);r.Inflate(-1,-1);g.FillRectangle(b,legendRect);b.Dispose();floatstartY=5;foreach(ChartLineclinchartData.Lines){Penp=newPen(cl.Color);p.Width=p.Width*4;SizeFtextsize=g.MeasureString(cl.Title,legendFont);floatlineY=startY+textsize.Height/2;g.DrawLine(p,r.X+7,lineY,r.X+25,lineY);g.DrawString(cl.Title,legendFont,newSolidBrush(foreColor),r.X+30,startY);startY+=(textsize.Height+2);}}}}关闭本页
相关信息· shell实例
· 真想好好睡上一觉!
· 把常访问的网址显示在收藏夹前面
· X.Org 7.4 正式发布
7717
26913
