I created a .ashx generic web handler that returns images. However, I wanted to return a meaningful response if there was any problem returning the requested image (for example, an invalid ID, missing file, corrupted file, etc). Since the application calling the web handler only expected an image, I needed to return the meaning response as an image. Here’s what I wrote:

Imports System.Drawing
Imports System.Windows.Forms

Public Function StringToBitmap(s As String, font As Drawing.Font, brush As Drawing.Brush) As Drawing.Bitmap
	Dim textSize As Drawing.Size = Windows.Forms.TextRenderer.MeasureText(s, font)
	Dim bitmap As New Drawing.Bitmap(textSize.Width, textSize.Height)

	Using graphics As Drawing.Graphics = Drawing.Graphics.FromImage(bitmap)
		graphics.DrawString(s, font, brush, 0, 0)
	End Using
	Return bitmap
End Function

I also created a small wrapper with a default font and brush:

Public Function StringToBitmap(s As String) As Drawing.Bitmap
	Return StringToBitmap(s, Drawing.SystemFonts.DefaultFont, Drawing.Brushes.Black)
End Function


Leave a Reply