[Silverlight] Watermarker un WriteableBitmap avec un texte
Salut à tous,
Dans mon projet actuel j’ai eu besoin de watermarker un WriteableBitmap avec un texte. Après quelques recherches et ne trouvant rien répondant à mon besoin, j’ai décidé de me créer une petite méthode d’extension.
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;
}
}
Pour faire rouler ce code vous aurez besoin de la librairie WritableBitmapEx.
Comme vous pouvez voir c’est assez simple. Vous avez juste besoin d’appeler la méthode Watermark et lui passer le texte à ajouter. Vous pouvez également passer des paramètres optionnels comme la couleur, l’opacité, la taille de la font ou si vous voulez un effet type DropShadow. J’aurais pu ajouter des paramètres comme la position ou la police du texte, mais libre à vous de les ajouter si vous voulez.
Voici ce que ce bout de code peut donner :

En espérant que ça vous aide.
Ce post vous a plu ? Ajoutez le dans vos favoris pour ne pas perdre de temps à le retrouver le jour où vous en aurez besoin :