Introduction/Inspiration
I was searching for similar stuff in the net for quite some time and found the article written by Manster. Before this article, I found few other articles too, but they didn't explain how to render image without saving it to the disk. After seeing this code and reading the posts in the feedback section by other members asking "How to show image in image control", I decided to get the thing done.
Testing the application
- Quite easy and simple, just extract the files and create a "testing" web application mapping to the extracted directory.
Or
- Add the Default.* and ImageGenerator.* files to your existing web application. Just type the URL in the browser.
Using the code
As I said, this article is based on Manster's article, I am not going to explain much how the Dynamic Image Generation works. You may read base article here.
In my demo project(default.aspx) I have used four elements.
Image
Control with default text set.
Image
Control to demonstrate Dynamic Image Generation.
- HTML Image element (
<img>
).
- One more HTML Image element with font size set.
For the value of ImageUrl
(Image
control)/ src
(HTML <img>
element), just pass the text you want to convert to image as HTML query string. E.g.:
<img src="ImageGenerator.aspx?imgtext=Hello&fontsize=24">
This will generate image text "Hello" with font size 24. Same way works with the Image
control, pass the ImageURL
parameter same as above (or just check the demo code). If you don't pass the query string, then you will see a "?" (default text). Default font size is set to 10.
Here comes the core which I copy, pasted from the site and converted to VB.NET code.
Dim sImageText As String
Dim iFontSize As Integer
sImageText = Server.UrlDecode(Request.QueryString("imgtext"))
iFontSize = CInt(Server.UrlDecode(Request.QueryString("fontsize")))
If sImageText.Trim.Length = 0 Then sImageText = "?"
If iFontSize = 0 Then iFontSize = 12
Dim bmpImage As New Bitmap(1, 1)
Dim iWidth As Integer = 0
Dim iHeight As Integer = 0
Dim MyFont As New Font("Verdana", iFontSize, _
System.Drawing.FontStyle.Bold, _
System.Drawing.GraphicsUnit.Point)
Dim MyGraphics As Graphics
MyGraphics = Graphics.FromImage(bmpImage)
iWidth = MyGraphics.MeasureString(sImageText, MyFont).Width
iHeight = MyGraphics.MeasureString(sImageText, MyFont).Height
bmpImage = New Bitmap(bmpImage, New Size(iWidth, iHeight))
MyGraphics = Graphics.FromImage(bmpImage)
MyGraphics.Clear(Color.White)
MyGraphics.TextRenderingHint = TextRenderingHint.AntiAlias
MyGraphics.DrawString(sImageText, MyFont, New SolidBrush(Color.Brown), 0, 0)
MyGraphics.Flush()
Response.ContentType = "image/gif"
bmpImage.Save(Response.OutputStream, ImageFormat.Gif)