Sunday, November 6, 2011

C# Image Watermark (Overlay) Example

It's often a good idea to stamp your own photos or images with your mark when distributing on the internet to discourage people from claiming them as their own work, or in case they just forget image attribution.

NOTE: This is an over simplified piece of code and is missing some functionality like
  • Image resolution syncing (ensuring base and watermark images have the same dpi). Otherwise the watermark could end up being stretched compared to it's native view.
  • Boundary checking (check that watermark is totally inside the base image).
  • Watermark transparency. A fully opaque watermark can distract from the content of the base image, or just look ugly. Transparency blends the watermark into the base image creating a nice effect.
  • Rounded watermark corners. Rounded corners are cool right so yeah gotta have them too.
A more comprehensive class to achieve these is available in my open source C# library BFLib hosted at Google Code: http://code.google.com/p/bflib/

Here is the simple piece of code that overlays one image on top of another:

//_baseImage is the photograph/image you want to put a watermark on
Bitmap _baseImage = new Bitmap("c:\myphoto.jpg");
//_stickerImage is ususally a small image with your logo or name.
Bitmap _watermarkImage = new Bitmap("c:\mystamp.jpg");

//Draw the watermark offset 10 pixels from the left and 10 pixels from the top of the base image.
Graphics canvas = Graphics.FromImage(_baseImage);
canvas.DrawImage(_watermarkImage,
new Rectangle(10, 10,
_watermarkImage.Width, _watermarkImage.Height),
0,
0,
_watermarkImage.Width,
_watermarkImage.Height,
GraphicsUnit.Pixel);

canvas.Save();
_baseImage.Save("c:\watermarked.jpg");


No comments:

Post a Comment