Introduction
Sometimes we need to add a watermark on an image. For example, adding a copyright or name on the image. We may also need to create watermark in documents.
In this blog and the code sample, I have explained how to write text on an image using C#. This code can be used in both, Windows or Web applications.
Step 1
In your Visual Studio, create a new folder and have the image in that that you want to add watermark to. Something like this:
Intially download.jpg will be like this.
In your project, import the following namesoace that provides classes to work with images.
Write the following code on a button click or any event where you want the watermark to be added on the image.
Code snippet
- string root = HttpContext.Current.Server.MapPath("~/Images/download.jpg");
- System.Drawing.Image bitmap = (System.Drawing.Image)Bitmap.FromFile(root);
- Font font = new Font("Arial", 20, FontStyle.Italic, GraphicsUnit.Pixel);
- Color color = Color.FromArgb(255, 255, 0, 0);
- Point atpoint = new Point(bitmap.Width / 2, bitmap.Height / 2);
- SolidBrush brush = new SolidBrush(color);
- Graphics graphics = Graphics.FromImage(bitmap);
- StringFormat sf = new StringFormat();
- sf.Alignment = StringAlignment.Center;
- sf.LineAlignment = StringAlignment.Center;
- graphics.DrawString("Madan S B", font, brush, atpoint, sf);
- graphics.Dispose();
- MemoryStream m = new MemoryStream();
- bitmap.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
- byte[] convertedToBytes = m.ToArray();
- string saveto= HttpContext.Current.Server.MapPath("~/Images/test.jpg");
- System.IO.File.WriteAllBytes(saveto, convertedToBytes );
In the above code, I create a Image object from the file. After that, I use a Brush and a Color object and create a string. The Graphics object is the one used to draw anything in GDI+. The DrawString method is used to draw on a surface. The surface can be an image.
After that, I use Graphics.Save method to same the image with text as a new image, text.jpg.
After executing above code, we will get new image with text, something like this.
Summary
In this blog, we are discussed how to add text to an image using C#.
I hope its helpful. Eat-> Code->Sleep->Repeat.