2008年7月25日 星期五

動態產生註冊文字圖檔

void BuildDynamicPic(string AvgRating)
{
if (AvgRating == null AvgRating.Length == 0) AvgRating = "0";
// 圖形
System.Drawing.Bitmap BMP1 = new System.Drawing.Bitmap(Server.MapPath("~/images/placeholder-100.jpg"));
//-----------------------------------------------------------------
//畫出文字
//-----------------------------------------------------------------

//定義繪圖元件
System.Drawing.Graphics formGraphics = System.Drawing.Graphics.FromImage(BMP1);

System.Drawing.Font drawFont = new System.Drawing.Font("John Handy LET", 32);
//定義筆刷
System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.White);
Single X = (AvgRating.Length > 1) ? 5 : 22;
Single Y = 15;
System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
//繪製文字
formGraphics.DrawString(AvgRating, drawFont, drawBrush, X, Y, drawFormat);
drawFont.Dispose();
drawBrush.Dispose();
formGraphics.Dispose();
//從另一張網頁 ShowBitmap 輸出
Session["BMP1"] = BMP1;
//在最後加入Guid是為了解決圖檔放在updatepanel中做非同步時該圖檔也要觸發重新抓取
imgAvgRating.ImageUrl = "ShowBitmap.aspx?imgID=BMP1&r=" + Guid.NewGuid().ToString();
imgAvgRating.Visible = true;
}


//在ShowBipmap.aspx.cs的Page_Load寫上
protected void Page_Load(object sender, EventArgs e)
{
System.Drawing.Bitmap BMP ;
BMP = (System.Drawing.Bitmap)Session[Request["imgID"].ToString()];
BMP.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
BMP.Dispose();
Response.End();
}


結果

沒有留言: