Introduction
Recently I came across the task of stamping image(s) without disturbing the image's contents at all. I was wondering about how I could do it. I searched a lot, but did not find a solution exactly how I wanted. So, after studying about the GDI+ library and spending some time and effort, I got my own solution. I think this code can help others who have the same or similar kinds of tasks on their hands. This code helps to stamp an image without disturbing its original contents. A stamp can be a blank image or an image with text written on it.
Using the Code
There are many classes like Bitmap
, Image
, Graphics
, Font
, Brush
, etc. to perform graphics operations using the .NET framework. To simplify the image-stamping process, let's look at the code that demonstrates how to stamp images.
Creating a stamp is as simple as creating the Bitmap
object itself by specifying its height and width. This task involves only three steps:
- Create the
Bitmap
object
- Create the
Graphics
object using the Bitmap
object
- Use the
DrawString()
method of the Graphics
class
Dim ImgStamp As New Bitmap(intWidth, intHeight)
Dim g As Graphics = Graphics.FromImage(ImgStamp)
g.DrawString("Test", New Font("Arial", 15, FontStyle.Bold), _
New SolidBrush(Color.Red), 25, 35)
ImgStamp.Save(YourPath & "\MyStamp.Tiff" )
ImgStamp.Save(YourPath & "\MyStamp.Tiff",_
System.Drawing.Imaging.ImageFormat.Tiff)
The DrawString()
method takes Font
and Brush
objects to draw the text on the Bitmap
. Here you can create your own Font
object by using FontDialog
's properties like fontName
, size and style in same way you can create a Brush
object using the Color
object. The last two parameters are a starting X and Y position for the text to be written on the Bitmap
. Here's the code to stamp the original image:
Dim OrgImg As New Bitmap(strImagePath)
Dim StampImg As New Bitmap(StampImagePath & "\MyStamp.Tiff")
Dim TarImg As New Bitmap(OrgImg.Width, OrgImg.Height + StampImg.Height)
Dim gr As Graphics = Graphics.FromImage(TarImg)
gr.DrawImage(OrgImg, 0, 0, OrgImg.Width, OrgImg.Height)
gr.DrawImage(StampImg, 0, OrgImg.Height, StampImg.Width, StampImg.Height)
TarImg.Save(YourPath & "\MyStamppedImage.Tiff")
The above code will create the new image file named MyStamppedImage.jpg with original content and additional stamp image pasted below, without disturbing content of original image file.
Points of Interest
This code creates only one stamp at the end of the content of the original image, but you can create more than one stamp on the same image and you can even create a stamp on top of the original content of the image. You can use the Color
object to create different colored stamps. By using the Color.FromArgb()
method, you can make any color to create background and foreground colors for the stamp. You can even compress the original or stamp image for further clarity.
History
- 20 August, 2007 -- Original version posted
- 22 August, 2007 -- Updated version of demo project