2010-05-06 29 views
1

我試圖以編程方式在ASP.Net中使用指定字體創建位圖。這個想法是,文本,字體名稱,大小顏色等將從變量傳入,並使用字體等文本的位圖將被返回。 但是,我一直在發現,我只能用特定字體使用下面的代碼。無法在ASP.Net中以編程方式使用某些字體

<div> 
    <% 
    string fontName = "Segoe Script"; //Change Font here 
    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(100, 100); 
    System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp); 
    System.Drawing.Font fnt = new System.Drawing.Font(fontName, 20); 
    System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Red); 
    graph.DrawString("Help", fnt, brush, new System.Drawing.Point(10, 10)); 

    bmp.Save(@"C:\Development\Path\image1.bmp"); 
    this.Image1.ImageUrl = "http://mysite/Images/image1.bmp"; 
    %> 
<asp:Label ID="Label1" runat="server" Text="Label" Font-Names="Segoe Script"> <%Response.Write("Help"); %></asp:Label> //Change font here 
<asp:Image ID="Image1" runat="server" /> 
</div> 

如果我被評論爲Arial或Verdana字體都的形象和標籤指示的區域改變字體名稱纔會顯示正確的字體。 但是,如果將兩個位置的字體名稱更改爲「Segoe腳本」,則該標籤將顯示在Segoe腳本中,但該圖像看起來像Arial。

更新:

基於這個問題here我能得到它的工作通過使用PrivateFontCollection()和加載像這樣的字體文件。

<div> 
    <% 
    string TypeFaceName = "Segoe Script"; 
    System.Drawing.Text.PrivateFontCollection fnts = new System.Drawing.Text.PrivateFontCollection(); 
    fnts.AddFontFile(@"C:\Development\Fonts\segoesc.ttf"); 
    System.Drawing.FontFamily fntfam = new System.Drawing.FontFamily(TypeFaceName); 
    System.Drawing.Font fnt = new System.Drawing.Font(fntfam, 13); 

    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(100, 100); 
    System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp); 
    System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Red); 
    graph.DrawString("Help", fnt, brush, new System.Drawing.Point(10, 10)); 

    bmp.Save(@"C:\Development\Path\Images\image1.bmp"); 
    this.Image1.ImageUrl = "http://MySite/Images/image1.bmp"; 
    %> 
    <asp:Label ID="Label1" runat="server" Text="Label" Font-Names="Segoe Script">  <%Response.Write("Help"); %></asp:Label> 
    <asp:Image ID="Image1" runat="server" /> 
    </div> 

回答

1

確保字體安裝在您的服務器上。

此外,如果兩個人同時查看頁面,您的代碼將會失敗。
您需要創建一個.ASHX處理程序,它接受查詢字符串中的參數並動態提供圖像。

+0

字體安裝在Web服務器上,我可以使用paint.net手動創建帶有字體的圖像。我發佈的代碼只是爲了查看是否可以完成。謝謝。 – etoisarobot 2010-05-06 15:06:28

0

你會遇到你的代碼的內存麻煩。所有GDI +對象都需要小心釋放或泄露行爲(即使GC最終會通過終結器清理,這可能爲時已晚,因爲未使用的非管理內存數量可能會導致應用程序更早斷開)。

此外,您可能希望使用特殊的IHttpHandler處理這種「動態文本」的請求,而不是創建「靜態」文件。

相關問題