[Silverlight] How to watermark a WriteableBitmap with a text
- by Benjamin Roux
Hello, In my current project, I needed to watermark a WriteableBitmap with a text. As I couldn’t find anything I decided to create a small extension method to do so. public static class WriteableBitmapEx
{
/// <summary>
/// Creates a watermark on the specified image
/// </summary>
/// <param name="input">The image to create the watermark from</param>
/// <param name="watermark">The text to watermark</param>
/// <param name="color">The color - default is White</param>
/// <param name="fontSize">The font size - default is 50</param>
/// <param name="opacity">The opacity - default is 0.25</param>
/// <param name="hasDropShadow">Specifies if a drop shadow effect must be added - default is true</param>
/// <returns>The watermarked image</returns>
public static WriteableBitmap Watermark(this WriteableBitmap input, string watermark, Color color = default(Color), double fontSize = 50, double opacity = 0.25, bool hasDropShadow = true)
{
var watermarked = GetTextBitmap(watermark, fontSize, color == default(Color) ? Colors.White : color, opacity, hasDropShadow);
var width = watermarked.PixelWidth;
var height = watermarked.PixelHeight;
var result = input.Clone();
var position = new Rect(input.PixelWidth - width - 20 /* right margin */, input.PixelHeight - height, width, height);
result.Blit(position, watermarked, new Rect(0, 0, width, height));
return result;
}
/// <summary>
/// Creates a WriteableBitmap from a text
/// </summary>
/// <param name="text"></param>
/// <param name="fontSize"></param>
/// <param name="color"></param>
/// <param name="opacity"></param>
/// <param name="hasDropShadow"></param>
/// <returns></returns>
private static WriteableBitmap GetTextBitmap(string text, double fontSize, Color color, double opacity, bool hasDropShadow)
{
TextBlock txt = new TextBlock();
txt.Text = text;
txt.FontSize = fontSize;
txt.Foreground = new SolidColorBrush(color);
txt.Opacity = opacity;
if (hasDropShadow) txt.Effect = new DropShadowEffect();
WriteableBitmap bitmap = new WriteableBitmap((int)txt.ActualWidth, (int)txt.ActualHeight);
bitmap.Render(txt, null);
bitmap.Invalidate();
return bitmap;
}
}
For this code to run, you need the WritableBitmapEx library.
As you can see, it’s quite simple. You just need to call the Watermark method and pass it the text you want to add in your image. You can also pass optional parameters like the color, the opacity, the fontsize or if you want a drop shadow effect. I could have specify other parameters like the position or the the font family but you can change the code if you need to.
Here’s what it can give
Hope this helps.