I have a scenario where the Watermark text size should be assigned automatically as per the Image size. I am new to C# drawing features. Please help me get some workaround for this.
Current Logic to apply watermark text with fixed size on the image
protected byte[] WatermarkImage(string PhysicalPath, string Watermarktext)
{
        byte[] imageBytes = null;
        if (File.Exists(PhysicalPath))
        {
            // This is the Name which will appear as a watermark on image.
            string watermark = Watermarktext;
            Image image = Image.FromFile(PhysicalPath);
            Graphics graphic;
            if (image.PixelFormat != PixelFormat.Indexed && image.PixelFormat != PixelFormat.Format8bppIndexed && image.PixelFormat != PixelFormat.Format4bppIndexed && image.PixelFormat != PixelFormat.Format1bppIndexed)
            {
                graphic = Graphics.FromImage(image);
            }
            else
            {
                Bitmap indexedImage = new Bitmap(image);
                graphic = Graphics.FromImage(indexedImage);
                // Draw the contents of the original bitmap onto the new bitmap.
                graphic.DrawImage(image, 0, 0, image.Width, image.Height);
                image = indexedImage;
            }
            graphic.SmoothingMode = SmoothingMode.AntiAlias & SmoothingMode.HighQuality;
            //This is the font for your watermark
            int size = 30; int opacity = 100;
            Font myFont = new Font("Arial", size, FontStyle.Bold, GraphicsUnit.Pixel);
            SolidBrush brush = new SolidBrush(Color.FromArgb(opacity, Color.Beige));
            //This gets the size of the graphic
            SizeF textSize = graphic.MeasureString(watermark, myFont);
            graphic.TranslateTransform(image.Width / 2, image.Height / 2);
            var angle = -45f;
            graphic.RotateTransform(angle);
            var x = -(textSize.Width / 2);
            var y = -(textSize.Height / 2);
            // Code for writing text on the image and showing its postion on images.
            //graphic.RotateTransform(45);
            PointF pointF = new PointF(x, y);
            graphic.DrawString(watermark, myFont, brush, pointF);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                image.Save(memoryStream, GetImageFormat(PhysicalPath));
                imageBytes = memoryStream.ToArray();
            }
        }
        return imageBytes;
}
                you just need to change your size value, 30 is a fixed and change it to below code:
int countOfChar = Watermarktext.Length;
int size = (image.Width + image.Height / 2) / countOfChar;
I tested your code with a little changes, and that worked for all image sizes and dimensions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With