DotNetCurry Logo

Watermark and Add Copyright Info to your Images on your Local drive using C# and VB.NET

Posted by: Suprotim Agarwal , on 12/14/2008, in Category WinForms & WinRT
Views: 75062
Abstract: Most of us, who run websites/blogs or host technical content, face issues of our images being copied and displayed on other blogs. One of the solutions to this problem is watermarking our images with our logo or watermarking the website name on the images.In this article, I will propose a desktop solution using Windows Forms, which can be used to watermark images before you upload the images to the site.
Watermark and Add Copyright Info to your Images on your Local drive using C# and VB.NET
 
Prevention is better than cure! Most of us, who run websites/blogs or host technical content, face issues of our images being copied and displayed on other blogs. There are a couple of techniques we can adopt to safeguard our copyrighted content and prevent people from doing so. One of them is watermarking our images with our logo or watermarking the website name on the images. A few weeks ago, I had discussed one such technique using ASP.NET. In this article, I will propose a desktop solution using Windows Forms, which can be used to watermark images before you upload the images to the site. This desktop solution basically saves us some processing and response time while watermarking images. Let us get started.
Create a Windows application. Drop a Button control (btnWatermark), a label(lblStatus) and a FolderBrowserDialog component from the ToolBox to the Form.
In the button click, open a dialog box using the FolderBrowerDialog component, which enables the user to select a folder containing images. We then loop through all images in that folder, create a filestream object and then pass it to the AddWatermark(). The AddWatermark method has been taken from a code sample posted by Rong-Chun over here
The AddWatermark accepts a FileStream and then draws the watermark on the image using the Graphics class. Here’s the code to do draw watermark on your images.
C#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
 
namespace WatermarkImages
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.folderBrowserDialog1.Description =
            "Select the images directory";
 
            // Disallow creation of new files using the FolderBrowserDialog.
            this.folderBrowserDialog1.ShowNewFolderButton = false;
        }
 
       
        private void btnWatermark_Click(object sender, EventArgs e)
        {
            string path = String.Empty;
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                path = folderBrowserDialog1.SelectedPath;
            }
 
            if (path == String.Empty)
            {
                lblStatus.Text = "Invalid directory..";
                return;
            }
 
 
            lblStatus.Text = String.Empty;                       
            Image img = null;
            string fullPath = String.Empty;
           
            try
            {
                string[] imgExtension = { "*.jpg", "*.jpeg", ".gif""*.bmp" };
                List<FileInfo> files = new List<FileInfo>();               
               
                DirectoryInfo dir = new DirectoryInfo(path);
               
                foreach (string ext in imgExtension)
                {
                    FileInfo[] folder = dir.GetFiles(ext, SearchOption.AllDirectories);
                    foreach (FileInfo file in folder)
                    {
                        FileStream fs = file.OpenRead();
                        fullPath = path + @"\" + file.Name ;
           
                        Stream outputStream = new MemoryStream();
                        AddWatermark(fs, "www.dotnetcurry.com", outputStream);
                        fs.Close();
                        file.Delete();
                        img = Image.FromStream(outputStream);
 
                        using (Bitmap savingImage = new Bitmap(img.Width, img.Height, img.PixelFormat))
                        {
                            using (Graphics g = Graphics.FromImage(savingImage))
                                g.DrawImage(img, new Point(0, 0));
                            savingImage.Save(fullPath, ImageFormat.Jpeg);            
                           
                        }
                      
                        img.Dispose();
                       
                    }
                }
                lblStatus.Text = "Processing Completed";
            }
            catch (Exception ex)
           {
               lblStatus.Text = "There was an error during processing..";           
            }
            finally
            {
                if (img != null)
                    img.Dispose();
            }
      }
 
 
        public void AddWatermark(FileStream fs, string watermarkText, Stream outputStream)
        {
            Image img = Image.FromStream(fs);               
            Font font = new Font("Verdana", 16, FontStyle.Bold, GraphicsUnit.Pixel);
            //Adds a transparent watermark with an 100 alpha value.
            Color color = Color.FromArgb(100, 0, 0, 0);
            //The position where to draw the watermark on the image
            Point pt = new Point(10, 30);
            SolidBrush sbrush = new SolidBrush(color);
 
            Graphics gr = null;
            try
            {
                gr = Graphics.FromImage(img);
            }
            catch
            {
                // http://support.microsoft.com/Default.aspx?id=814675
                Image img1 = img;
                img = new Bitmap(img.Width, img.Height);
                gr = Graphics.FromImage(img);
                gr.DrawImage(img1, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
                img1.Dispose();
            }
                       
            gr.DrawString(watermarkText, font, sbrush, pt);
            gr.Dispose();
           
            img.Save(outputStream, ImageFormat.Jpeg);
        }
    
    }
}
 
VB.NET
Imports System
Imports System.Collections.Generic
Imports System.Drawing
Imports System.Windows.Forms
Imports System.IO
Imports System.Drawing.Imaging
 
Namespace WatermarkImages
      Partial Public Class Form1
            Inherits Form
            Public Sub New()
                  InitializeComponent()
                  Me.folderBrowserDialog1.Description = "Select the images directory"
 
                  ' Disallow creation of new files using the FolderBrowserDialog.
                  Me.folderBrowserDialog1.ShowNewFolderButton = False
            End Sub
            Private Sub btnWatermark_Click(ByVal sender As Object, ByVal e As EventArgs)
                  Dim path As String = String.Empty
                  Dim result As DialogResult = folderBrowserDialog1.ShowDialog()
                  If result = DialogResult.OK Then
                        path = folderBrowserDialog1.SelectedPath
                  End If
 
                  If path = String.Empty Then
                        lblStatus.Text = "Invalid directory.."
                        Return
                  End If
 
 
                  lblStatus.Text = String.Empty
                  Dim img As Image = Nothing
                  Dim fullPath As String = String.Empty
 
                  Try
                        Dim imgExtension() As String = { "*.jpg", "*.jpeg", ".gif", "*.bmp" }
                        Dim files As List(Of FileInfo) = New List(Of FileInfo)()
 
                        Dim dir As New DirectoryInfo(path)
 
                        For Each ext As String In imgExtension
                              Dim folder() As FileInfo = dir.GetFiles(ext, SearchOption.AllDirectories)
                              For Each file As FileInfo In folder
                                    Dim fs As FileStream = file.OpenRead()
                                    fullPath = path & "\" & file.Name
 
                                    Dim outputStream As Stream = New MemoryStream()
                                    AddWatermark(fs, "www.dotnetcurry.com", outputStream)
                                    fs.Close()
                                    file.Delete()
                                    img = Image.FromStream(outputStream)
 
                                    Using savingImage As New Bitmap(img.Width, img.Height, img.PixelFormat)
                                          Using g As Graphics = Graphics.FromImage(savingImage)
                                                g.DrawImage(img, New Point(0, 0))
                                          End Using
                                          savingImage.Save(fullPath, ImageFormat.Jpeg)
 
                                    End Using
 
                                    img.Dispose()
 
                              Next file
                        Next ext
                        lblStatus.Text = "Processing Completed"
                  Catch ex As Exception
                     lblStatus.Text = "There was an error during processing.."
                  Finally
                        If img IsNot Nothing Then
                              img.Dispose()
                        End If
                  End Try
            End Sub
 
 
            Public Sub AddWatermark(ByVal fs As FileStream, ByVal watermarkText As String, ByVal outputStream As Stream)
                  Dim img As Image = Image.FromStream(fs)
                  Dim font As New Font("Verdana", 16, FontStyle.Bold, GraphicsUnit.Pixel)
                  'Adds a transparent watermark with an 100 alpha value.
                  Dim color As Color = Color.FromArgb(100, 0, 0, 0)
                  'The position where to draw the watermark on the image
                  Dim pt As New Point(10, 30)
                  Dim sbrush As New SolidBrush(color)
 
                  Dim gr As Graphics = Nothing
                  Try
                        gr = Graphics.FromImage(img)
                  Catch
                        ' http://support.microsoft.com/Default.aspx?id=814675
                        Dim img1 As Image = img
                        img = New Bitmap(img.Width, img.Height)
                        gr = Graphics.FromImage(img)
                        gr.DrawImage(img1, New Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel)
                        img1.Dispose()
                  End Try
 
                  gr.DrawString(watermarkText, font, sbrush, pt)
                  gr.Dispose()
 
                  img.Save(outputStream, ImageFormat.Jpeg)
            End Sub
 
End Class
End Namespace
 
 
I have added a few .gif, .jpg and .bmp images at C:\MyImageFolder. Run the application. Click the button to open the FolderBrowserDialog and select the image folder of your choice as shown below.
FolderBrowser
When you click OK, the images are processed and watermark is added to the images.
Processing
In the example, I have added the text “www.dotnetcurry.com” to the image as shown below.
Watermark
I am sure this solution would help out website owners to protect their copyrighted images. I hope this article was useful and I thank you for viewing it.
 If you liked the article,  Subscribe to my RSS Feed or Subscribe Via Email
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Vivek on Sunday, December 14, 2008 3:42 PM
Good Work!!!
I like this article.

Vivek
http://dotnetguts.blogspot.com

Comment posted by Ramesh Bandi on Wednesday, October 28, 2009 10:01 AM
Saved a lot of time. Thanks!

Ramesh Bandi
Comment posted by sagar on Thursday, April 17, 2014 8:02 AM
really nice article sir

but if u possible in web base application ?
Comment posted by Hardik on Saturday, April 11, 2015 2:44 PM
Can we do reverse the process ? Means remove watermark from images using .net ??