日期:2009-07-29  浏览次数:20420 次

Adding text to an image in memory
This article covers using the System.Drawing.Bitmap and drawBrush to draw text on a bitmap in memory. You could use this code as a base to create dynamic navigational buttons for your site.

In this code snippet we're going to provide will enable you to add text to an image in memory. One use for this code may be to open a file on the file system and add some text to the image, then stream the image out to the user. This could come in handy if you want to create navigational buttons for your Web site dynamically based on a request or dynamically create Banners via .Net code.


The first thing we do in the code is declare a bitmap variable, in this example "bmap". The next line in this example grabs data in the clipboard of the PC. This could very well be any image in memory such as an image file opened from the local file system.

Dim bmap As Image
'pull an image from memory, could also be from the file system.
bmap = CType(data.GetData(GetType(System.Drawing.Bitmap)), Image)
'here's where we modify the image in memory
Dim g As Graphics = Graphics.FromImage(bmap)
'now prepare our brush to draw the text onto the image.
Dim drawFont As New Font("Arial", 10, FontStyle.Bold, GraphicsUnit.Millimeter)
Dim drawBrush As New SolidBrush(Color.Red)
'figure out where we want to place the text getting the x & y coordinate.
Dim xPos As Integer = bmap.Height - (bmap.Height - 25)
Dim yPos As Integer = 3
'now draw the date using "Now".
g.DrawString(Now, drawFont, drawBrush, xPos, yPos)
'check to see if the property to save the file is enabled.

Now that we have a modified image in memory we can save the file to disk and generate a thumbnail image as well to present in the Web page for later viewing.

Dim sPicPath As String = "C:\Path to your file store\filename.jpg"
Dim sPreFix As String = "C:\image file path\"
'now declare another image to store our thumbnail image.
Dim smBmap As Image
'now we're going to get a thumbnail image from the bitmap we worked
'with earlier in the method.
smBmap = bmap.GetThumbnailImage(bmap.Width, bmap.Height, Nothing, Nothing)
'save the image to our path and save it as a jpeg.
smBmap.Save(sPicPath, Imaging.ImageFormat.Jpeg)
'now save a copy of the original image to the local disk.
bmap.Save(Replace(sPreFix, "\images", "") & ".jpg", Imaging.ImageFormat.Jpeg)
bmap = Nothing
smBmap = Nothing

This code should get you started working with images in memory and maybe provide a base to get started creating dynamic images for your Website.