E:\web\learnaspcom\htdocs\freebook\learn\ubtoc.xml LearnAsp.com - ASP ASP.net Free Lessons
Search Search

#1 worldwide
FREE Coding Lessons

since 1996
   THE BEST WAY to learn ASP & Asp.net!
Advertise Here!
click for details
Credits Host:
DiscountASP.net
Server Admin:
The "Team"
Contact Info.
Charles M. Carroll
<Asp.net blog>
<personal site>
xxx

User Controls For Text2Graphics
by Charles Carroll and Mac Kloberg

This page demonstrates a very useful in the real-world a User Control to encapsulate grabbing the resultant string a website would generate if invoked from a browser.

Simple page:

   filename=/experiments/gdiPage/text2Graphic.aspx

<Test Script Below>


<%@ Register TagPrefix="LearnAsp" tagname="Text2Graphic" src="text2Graphic.ascx"%>
<script language="VB" runat="server">
    sub page_load(s as object, e as eventargs)    
    end sub
</script>
<html><head><title>xxxxx</title></head>
<body bgcolor="#FFFFFF">
<form runat="server">
<!-- #FFCCFF Our Pink -->
<!-- #CCE6FF Our Blue -->
<LearnAsp:Text2Graphic 
    url="http://www.cnn.com"
    text="CNN" ForeColor="black" BackColor="#FFCCFF" 
    width="100" height="30"
    fontName="Arial" fontsize="11" customfont=""
    runat="server"/>
<LearnAsp:Text2Graphic 
    url="http://www.theonion.com"
    text=" The Onion" ForeColor="white" BackColor="skyblue" 
    width="100" height="30"
    fontName="Arial" fontsize="10" customfont=""
    runat="server"/>    
<LearnAsp:Text2Graphic 
    url="http://groups.yahoo.com/group/AspNetAnyQuestionIsOk"
    text=" ASP.net Free Help" ForeColor="white" BackColor="red" 
    width="150" height="30"
    fontName="Arial" fontsize="10" customfont=""
    runat="server"/>    
<LearnAsp:Text2Graphic 
    url="http://wwww.asptraining.com"
    text="Training" ForeColor="black" BackColor="orange" 
    width="100" height="30"
    fontName="Arial" fontsize="11" customfont=""
    runat="server"/>
<LearnAsp:Text2Graphic 
    url="http://docs.aspng.com/quickstart/aspplus/samples/classbrowser/vb/classbrowser.aspx"
    text="Object Browser" ForeColor="white" BackColor="purple" 
    width="150" height="30"
    fontName="Arial" fontsize="10" customfont=""
    runat="server"/>    
<LearnAsp:Text2Graphic 
    url="http://groups.yahoo.com/group/AspNetMetroArea"
    text="UserGroup" ForeColor="black" BackColor="pink" 
    width="100" height="30"
    fontName="Arial" fontsize="10" customfont=""
    runat="server"/>

</form></html></head>

The User Control:

filename=/experiments/gdiPage/text2Graphic.ascx


<script language="vb" runat="server">
public Alt as string
public BackColor as string
public CustomFont as string
public FontName as string
public FontSize as integer
public ForeColor as string
public Height as integer
public Text as string
public URL as string
public Width as integer
sub page_load(s as object, e as eventargs)
    Dim sb1 as new stringbuilder
    with sb1
        .append("http://www.learnasp.com/experiments/gdiPage/makegraphic.aspx?")
        .append("tx=")
        .append(server.urlencode(text))
        .append("&fs=")
        .append(fontsize)
        .append("&wi=")
        .append(width)
        .append("&he=")
        .append(height)
        .append("&cf=")
        .append(customfont)
        .append("&fo=")
        .append(fontName)
        .append("&fc=")
        .append(server.urlencode(ForeColor))
        .append("&bc=")
        .append(server.urlencode(BackColor))
    end with
    img1.Alt=Alt
    img1.src=sb1.ToString()
    hyp1.navigateURL=URL
end sub
</script>
<asp:hyperlink id="hyp1" runat="server">
<img ID="img1" border="0" runat="server" />
</asp:hyperlink>

The Source Code for the Page that does the GDI+ and Caching:

   filename=/experiments/gdiPage/makeGraphic.aspx

<Test Script Below>


<%@ Import NameSpace="System.IO"%>
<%@ Import NameSpace="System.Web"%>
<%@ Import NameSpace="System.Drawing"%>
<%@ Import NameSpace="System.Drawing.Text"%>
<%@ Import NameSpace="System.Drawing.Imaging"%>
<%@ Import NameSpace="System.Drawing.Drawing2D"%>
<script language="vb" runat="server">
    'Private variables
    'Private htDrawingParameters As New Hashtable()
    Private oBitmap As Bitmap = Nothing
    Private oTmpBitmap As Bitmap = Nothing
    Private tempStream As New MemoryStream()
    Private oDi As Graphics = Nothing
    Private oTmpI1 As Graphics = Nothing
    Private stringSize As SizeF
    Private TrueFont As Font
    Private strCacheSw As String = ""
    Private strError As String
    Private nWidth As Integer
    Private nHeight As Integer
    Private gWidth As Integer
    Private gHeight As Integer
    Private FontSize As Integer
    Private Text As String
    Private LoadCustomFont As Boolean
    Private FontFamilyName As String
    Private CustomFontCollection As PrivateFontCollection
    Private CustomFontFamily As FontFamily
    Private ForeColor As System.Drawing.Color
    Private BackColor As System.Drawing.Color

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim loop1, loop2 As Integer
        Dim arr1(), arr2() As String
        Dim coll As NameValueCollection
        Dim CacheKey As String = ""

        Response.Expires = 0
        ReadInput()

        If strError <> "" Then
            Response.Write(strError)
            Return
        End If

        'Build a cache key for this request
        coll = Request.QueryString
        arr1 = coll.AllKeys
        For loop1 = 0 To arr1.GetUpperBound(0)
            arr2 = coll.GetValues(loop1)
            For loop2 = 0 To arr2.GetUpperBound(0)
                CacheKey += arr1(loop1) & ":" & CStr(loop2) & ":" & arr2(loop2)
            Next loop2
        Next loop1

        ' Check Cache to see if this thing has been rendered before
        oBitmap = CType(Cache(CacheKey), Bitmap)
        If IsNothing(oBitmap) Then
            'Draw the requested image
            DrawText()
            'Put this image into the cache for future use
            Cache.Insert(CacheKey, oBitmap)
        End If

        If strError <> "" Then
            Response.Write(strError)
            Return
        End If

        'Return the image
        ReturnImage()

        If strError <> "" Then
            Response.Write(strError)
            Return
        End If

    End Sub

    Private Sub ReadInput()
        'Text
        If Request.QueryString("tx") Is Nothing Then
            Text = ""
        Else
            Text = System.Web.HttpUtility.HtmlDecode(Request.QueryString("tx"))
        End If
        If Text = String.Empty Then Text = ""

        'Font Size
        FontSize = -1
        If Not Request.QueryString("fs") Is Nothing AndAlso IsNumeric(Request.QueryString("fs")) Then
            FontSize = Integer.Parse(Request.QueryString("fs"))
        End If
        If FontSize = -1 Then FontSize = 11


        'Width
        gWidth = -1
        If Not Request.QueryString("wi") Is Nothing AndAlso IsNumeric(Request.QueryString("wi")) Then
            gWidth = Integer.Parse(Request.QueryString("wi"))
        End If
        If gWidth = -1 Then gWidth = 100


        'Height
        gHeight = -1
        If Not Request.QueryString("he") Is Nothing AndAlso IsNumeric(Request.QueryString("he")) Then
            gHeight = Integer.Parse(Request.QueryString("he"))
        End If
        If gHeight = -1 Then gHeight = 100

        'Custom Font Switch
        If Request.QueryString("cf") Is Nothing Then
            LoadCustomFont = False
        Else
            LoadCustomFont = False
            Try
                LoadCustomFont = System.Boolean.Parse(Request.QueryString("cf"))
            Catch
            End Try
        End If

        'Font
        TrueFont = Nothing
        If Not LoadCustomFont Then
            Try
                TrueFont = New Font(Request.QueryString("fo"), FontSize, FontStyle.Bold)
            Catch
            End Try
        Else
            Try
                FontFamilyName = "custom"
                CustomFontCollection = New PrivateFontCollection()
                'CustomFontCollection.AddFontFile("C:\Inetpub\wwwroot\Kascade\Fonts\blippok.ttf")
                CustomFontCollection.AddFontFile(Server.MapPath(System.Web.HttpUtility.HtmlDecode(Request.QueryString("fo"))))
                CustomFontFamily = CustomFontCollection.Families(0)
                TrueFont = New Font(CustomFontFamily, FontSize, FontStyle.Bold, GraphicsUnit.Pixel)
            Catch
            End Try
        End If
        If TrueFont Is Nothing Then
            TrueFont = New Font("Arial", FontSize, FontStyle.Regular)
        End If

        'Foreground color
        ForeColor = Color.DarkGray
        If Not Request.QueryString("fc") Is Nothing Then
            If Not Request.QueryString("fc").Trim = String.Empty Then
                Try
                    ForeColor = ColorTranslator.FromHtml(HttpUtility.UrlDecode(Request.QueryString("fc")))
                Catch
                End Try
            End If
        End If

        'Background color
        BackColor = Color.White
        If Not Request.QueryString("bc") Is Nothing Then
            If Not Request.QueryString("bc").Trim = String.Empty Then
                Try
                    BackColor = ColorTranslator.FromHtml(HttpUtility.UrlDecode(Request.QueryString("bc")))
                Catch
                End Try
            End If
        End If

    End Sub

    Private Sub DrawText()
        Dim oPen1 As Pen
        MeasureTextSize()
        nHeight = nHeight
        nWidth = nWidth
        oBitmap = GetNewBitmap()
        oDi = GetNewGfx(oBitmap)
        oDi.Clear(BackColor)
        oDi.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias
        oDi.SmoothingMode = SmoothingMode.AntiAlias
        Dim heightText As Single
        heightText = Convert.ToSingle((gHeight / 2) - (nHeight / 2))
        oDi.DrawString(Text, TrueFont, New SolidBrush(ForeColor), 0, heightText)

    End Sub

    Private Sub ReturnImage()
        Trace.Write("DynaImager.vb:Return Image", "Called")
        Dim oEncoderParameters As New EncoderParameters()
        'Return finished image
        Try
            oBitmap.Save(tempStream, ImageFormat.Png)
            'oBitmap.Save(tempStream, ImageFormat.jpg)
            Response.ClearContent()
            Response.ContentType = "image/png"
            'Response.ContentType = "image/jpg"
            Trace.Write("DynaImager.vb:", "Writing Image!")
            Response.BinaryWrite(tempStream.ToArray())
            Response.End()
        Catch
            'Write possible error
            strError = Err.Description
            Trace.Write("DynaImager.vb:Return Image", "Error Detected: " & strError)
        Finally
            'Cleanup            
            If Not IsNothing(oDi) Then oDi.Dispose()
            'Leave the bitmap alone, otherwise the cache breaks
            'If Not IsNothing(oBitmap) Then oBitmap.Dispose()
        End Try
    End Sub

    'Graphical helper functions
    '==========================
    Private Function MeasureTextSize() As Integer
        'Determine image size by text width
        oTmpBitmap = New Bitmap(1, 1, PixelFormat.Format24bppRgb)
        oTmpI1 = GetNewGfx(oTmpBitmap)
        stringSize = oTmpI1.MeasureString(Text, TrueFont)
        nWidth = CType(stringSize.Width, Integer)
        nHeight = CType(stringSize.Height, Integer)
        oTmpI1.Dispose()
        oTmpBitmap.Dispose()
    End Function

    Private Function GetNewBitmap() As Bitmap
        GetNewBitmap = New Bitmap(gWidth, gHeight, PixelFormat.Format24bppRgb)
    End Function

    Private Function GetNewGfx(ByRef oBMap As Bitmap) As Graphics
        GetNewGfx = Graphics.FromImage(oBMap)
        GetNewGfx.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
        'GetNewGfx.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
    End Function
</script>
Chaz Wish List
Tall Tip $5
Grande Tip $20
Venti Tip $39
Tip Jar Thanks
2004 Thanks
2005 Thanks
HUGE Tip -love site