There’s many cases when you may want to watermark images on your website including:
- Protecting copyrighted content
- Showing previews of premium content
- Identifying the origin of original content
And many more..
We’ll take a look at using the Razor WebImage helper to watermark images on your website easily and efficiently.
Adding the Microsoft.Web.Helpers Library
To add the Microsoft.Web.Helpers library, install NuGet, and install the Microsoft.Web.Helpers package. Also, include the System.Web.Helpers package included with ASP.NET MVC 3.
Our Image Displaying Website
Our website will be a simple website that takes in a view model containing pictures to display and outputs them to a page. We’re going to use the sample images supplied with Windows 7 for this demo.
Above is our simple display ViewModel, with a list of Image URL’s of images to display.
We’ll modify the Index action method of the HomeController supplied with the normal MVC3 project template as below.
Here were returning the results of GetViewModel, which merely populates the view model with the filenames from the images we want to display. This would likely come from a database in any real solution.
This results in the following index page:
Now, let see how we could protect these images using the WebImage helper to add watermarks as we display them.
Adding Watermarks with WebImage
First, we’re going to move our image tag into a partial view called Image.
Next, we’ll create an Action Method that will apply a watermark to our image.
Here, we’re loading the image supplied in the URL, and adding the following watermark image below.
The AddImageWatermark function allows you to specify the size, position, and padding of your watermark. I’m using the defaults, with our image being 150×150 pixels, displaying on the bottom right of the source image with a 5 pixel padding.
Now, we’ll need to replace our img tag in our Index page with a call to render the child action. Our new Index.cshtml is below.
In addition to adding an image watermark, we can add a text watermark as well. Below is a sample where we’ve replaced the image watermarking code with the text watermarking code, and show the resulting output.