How to Add a Watermark to an Image In C#

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. 
  1. using System.Drawing;  
Write the following code on a button click or any event where you want the watermark to be added on the image.
 
Code snippet
  1. string root = HttpContext.Current.Server.MapPath("~/Images/download.jpg");    
  2. System.Drawing.Image bitmap = (System.Drawing.Image)Bitmap.FromFile(root); // set image     
  3. Font font = new Font("Arial", 20, FontStyle.Italic, GraphicsUnit.Pixel);    
  4. Color color = Color.FromArgb(255, 255, 0, 0);    
  5. Point atpoint = new Point(bitmap.Width / 2, bitmap.Height / 2);    
  6. SolidBrush brush = new SolidBrush(color);    
  7. Graphics graphics = Graphics.FromImage(bitmap);    
  8. StringFormat sf = new StringFormat();    
  9. sf.Alignment = StringAlignment.Center;    
  10. sf.LineAlignment = StringAlignment.Center;    
  11. graphics.DrawString("Madan S B", font, brush, atpoint, sf);    
  12. graphics.Dispose();    
  13. MemoryStream m = new MemoryStream();    
  14. bitmap.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);    
  15. byte[] convertedToBytes = m.ToArray();    
  16. string saveto= HttpContext.Current.Server.MapPath("~/Images/test.jpg");    
  17. 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.
 
Here is a detailed article on this topic: Watermark Utility In C#