(Print this page)

Writing text on an image
Published date: Sunday, January 11, 2009
On: Moer and Éric Moreau's web site

This month article will be short and sweet and ... hopefully useful!

Last week, a friend of mine asked me how to add text to an image, something like a copyright notice on pictures. I first thought it was a challenge but I quickly discovered that with all the tools provided by the .Net Framework it really isn’t one! The only challenge here is to know/discover that all those things already exist.

The code you can download for this article was created using VB2008 SP1. If you still use VS2005, it would be exactly the same code as nothing is specific to the latest version of the framework.

Opening an image

I have already written an article on how to use the File Dialog component so I won’t spend time on this. If you want to read about it, you can read my article of June 2003 titled “Common dialogs”.

The code I have to write looks like this:

Private Sub btnLoadImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim o As New OpenFileDialog()

    o.Title = "Select the image to open"
    o.Filter = "Bitmap image|*.bmp|Jpeg image|*.jpg|All|*.*"
    If o.ShowDialog = DialogResult.OK Then
        If Not String.IsNullOrEmpty(o.FileName) Then
            Try
                PictureBox1.Load(o.FileName)
            Catch ex As Exception
                MessageBox.Show("The image you are trying to load is not supported", _
                                "Invalid image", _
                                MessageBoxButtons.OK, _
                                MessageBoxIcon.Exclamation)
            End Try
        End If
    End If
    o.Dispose()
    o = Nothing
End Sub

Writing some text on an image

I thought that it would have been though to do this part. But it appears that it takes less than 10 lines of code.

The required code looks like this:

Private Sub btnWriteText_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    If PictureBox1.Image Is Nothing Then
        MessageBox.Show("You must load an image first!!!", _
                        "Load an image", _
                        MessageBoxButtons.OK, _
                        MessageBoxIcon.Exclamation)
    Else
        Dim bm As Bitmap = CType(PictureBox1.Image, Bitmap)
        Dim g As Graphics = Graphics.FromImage(bm)
        Dim f As New Font("Arial", 12)
        Dim b As Brush = New SolidBrush(Color.White)

        g.DrawString(txtMessage.Text, f, b, 5, 5)

        Me.PictureBox1.Image = bm
    End If
End Sub
Here are the big steps of code that you see in here:
  • The first thing you see here is a validation to make sure that we really have an image.
  • The image contained into the PictureBox control is casted into a bitmap (no matter what was the original format).
  • An instance of the Graphics class is created and initialized using the Graphics.FromImage method using the bitmap we just got.
  • A Font and a Brush object are also created and initialized. These 2 objects will be used in the next step to write the string on the image. You may want to change the font family, font size, color ... or anything to fits your own need.
  • The ultimate step is to use the DrawString method of the Graphics instance to write the string (mine is coming from a TextBox control on the form) using the font and the brush just initialized. The last 2 parameters are the coordinates where the string will be written.
  • The final step is to display our new image into the PictureBox control.
Because the brush here is White, you won’t see much of your text if your image is white in the top left corner! If you download the code that goes with this article, you will find a method that writes the same string 5 times in black to create the illusion of a black border around each letter.

Figure 1: Me and Cinderella

Saving the image

The easiest way to save the image back to disk is to use the Image.Save method of the PictureBox control. Once again, I use the common dialogs to ask the user where to save new image, what name to use and I also let the user select one of the 3 following formats: Bitmap, Jpeg, GIF.

This is the code I need:

Private Sub btnSaveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    If PictureBox1.Image Is Nothing Then
        MessageBox.Show("You must load an image first!!!", _
                        "Load an image", _
                        MessageBoxButtons.OK, _
                        MessageBoxIcon.Exclamation)
    Else
        Dim o As New SaveFileDialog()

        o.Title = "Save your new image"
        o.Filter = "Bitmap image|*.bmp|Jpeg image|*.jpg|Gif image|*.gif"
        If o.ShowDialog = DialogResult.OK Then
            If Not String.IsNullOrEmpty(o.FileName) Then
                Select Case o.FilterIndex
                    Case 1
                        PictureBox1.Image.Save(o.FileName, Imaging.ImageFormat.Bmp)
                    Case 2
                        PictureBox1.Image.Save(o.FileName, Imaging.ImageFormat.Jpeg)
                    Case 3
                        PictureBox1.Image.Save(o.FileName, Imaging.ImageFormat.Gif)
                End Select
            End If
        End If
        o.Dispose()
        o = Nothing
    End If
End Sub

Conclusion

I was expecting more challenge but I was happy to discover that the .Net Framework is full of resources for handling that kind of requirements.


(Print this page)