心所欲生案
要是沒有外部的元件支援,有一些東西是 asp 無法辦到的,也就是動態產生圖案 - 不管是圖表、橫幅廣告、或是簡單的圖形計數器。幸運的是,這在 asp.net 中已經改變了 - 使用內建的方法,圖案可以動態產生以及能夠用最大限度的組態設定能力傳送到 client 端,且很容易辦到。
使用本文章的原始程式碼必須在 webserver 安裝 microsoft .net framework sdk。同時我也假設讀者對 c# 程式有一定程度的認識。
產生圖案
在還沒感受到 asp.net 龐大壓力下,我做了一個較乏味簡單的指令行程式,然後使用這個原始程式碼作為我們 asp.net script 的基礎。所不同的是這個指令行會將圖案儲存為一檔案,而 asp.net script 將他送到 client 端。
現在,我們的範例程式做了什麼?就像一般常見的,一開始我們使用一般喜歡用的 "hello world" 程式,文字會輸出成一圖案檔,然後圖案會依據目前所選定的字型以及字型大小,產生同樣大小的 "hello world" 文字(因此,要產生特大的圖像就無法計算)
下面的 script (pagecounter.cs) 是典型簡單的指令行程式: 忽略包裹在周圍的 class , 只有函式 main執行時會被呼叫,這也就是我們產生圖案所在的程式。
using system; using system.io; using system.drawing; using system.drawing.imaging; public class ctestbitmapfunctionality { public static void main() { bitmap newbitmap = null; graphics g = null ; try { font fontcounter = new font("lucida sans unicode", 12); // calculate size of the string. newbitmap = new bitmap(1,1,pixelformat.format32bppargb); g = graphics.fromimage(newbitmap); sizef stringsize = g.measurestring("hello world", fontcounter); int nwidth = (int)stringsize.width; int nheight = (int)stringsize.height; g.dispose(); newbitmap.dispose(); newbitmap = new bitmap(nwidth,nheight,pixelformat.format32bppargb); g = graphics.fromimage(newbitmap); g.fillrectangle(new solidbrush(color.white), new rectangle(0,0,nwidth,nheight)); g.drawstring("hello world", fontcounter, new solidbrush(color.black), 0, 0); newbitmap.save("c:\\test.png", imageformat.png); } catch (exception e) { console.writeline(e.tostring()); } finally { if (null != g) g.dispose(); if (null != newbitmap) newbitmap.dispose(); } } }這程式做了什麼?不管怎樣,結果圖案 test.png 會儲存在 drive c:
圖案如何產生?為了解原因,我們必須詳細來看一下原始碼。首先,圖案大小必須是和要呈現的文字字型 "hello world" 大小一樣,因此,我會先計算文字大小,同時為達目的,我使用一個 size 1 x 1 的仿製圖案,當我計算完成,我抓取圖案然後產生一適當的大小圖案。
原始碼中有趣的一點是 graphics 物件。當我要產生圖像為何需要這物件呢? 理由是這是我要畫進去的圖案情境 (context) - 我可以在螢幕、印表機以及記憶體使用圖案情境 - 正確來說就是 bitmap。圖案情境允許我在任何設備執行繪圖操作 (既時是虛擬的)。
使用 drawstring,我現在可以根據白色背景 (使用 fillrectangle 產生) 的長方形規格輸出文字 "hello world"。圖案完成了,我必須把它存到磁碟中。曾經有過自己設計過圖案檔格式都知道這是一件困難的事,使用 gdi+ (graphics device interface) 就不是如此 - 我們只要使用一簡單的命令就行了:
newbitmap.save("c:\\test.png", imageformat.png);就這樣了! 只要將 imageformat.png 交換成 imageformat.jpeg,你就能有 jpeg 的檔案。簡單的使用圖案,這就是我們一直想要的。
現在只是有個例外處理有待解釋:一些函式會造成例外(例如,
-
相关文章
2秒记住本站域名
玩过泡泡龙吗?Readygo?Go! 再加上.Com.Cn的后缀,那就是大名小顶的ReadyGo.com.cn
