Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Created December 20, 2023 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjoerntx/34ae2b25cea6a7c79822e587a5533f5e to your computer and use it in GitHub Desktop.
Save bjoerntx/34ae2b25cea6a7c79822e587a5533f5e to your computer and use it in GitHub Desktop.
using System.Drawing;
using System.Text;
public static class WatermarkGenerator
{
// Create an SVG watermark with centered text and rotation
public static byte[] CreateSVGWatermark(string text, int rotation, Color color, Font font)
{
// Guess the size of the SVG image including rotation
SizeF size = MeasureTextSize(text, font);
// Convert font to CSS style
string fontCssStyle = GetFontCssStyle(font);
// Convert color to hex
string colorHex = ColorToHex(color);
// Generate SVG markup
string svgMarkup = GenerateSvgMarkup(text, rotation, size, fontCssStyle, colorHex);
return Encoding.ASCII.GetBytes(svgMarkup);
}
private static SizeF MeasureTextSize(string text, Font font)
{
using (Graphics graphics = Graphics.FromImage(new Bitmap(1, 1)))
{
return graphics.MeasureString(text, font);
}
}
private static string GetFontCssStyle(Font font)
{
return $"font-family: {font.FontFamily.Name}; font-size: {font.Size}px; font-weight: {(font.Bold ? "bold" : "normal")};";
}
private static string ColorToHex(Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
private static string GenerateSvgMarkup(string text, int rotation, SizeF size, string fontCssStyle, string colorHex)
{
return $@"<svg xmlns='http://www.w3.org/2000/svg' width='{size.Width}' height='{size.Width}' viewBox='0 0 {size.Width} {size.Width}' preserveAspectRatio='none'>
<text x='{size.Width / 2}' y='{size.Width / 2}' text-anchor='middle' alignment-baseline='middle' transform='rotate({rotation} {size.Width / 2} {size.Width / 2})' style='{fontCssStyle} fill: {colorHex};'>{text}</text>
</svg>";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment