JG Vimalan's Blog

Sharing is caring :)

Watermark to an Image using C#

There are often situations where an image is stored in database and it needs to be displayed in a web page with watermark. The following method written using C# accepts a byte array, add watermark text to it and returns the updated image as byte array.





        private static byte[] AddWatermark(Byte[] bytes)
        {
            byte[] convertedToBytes;

            using (MemoryStream originalImageMemoryStream = new MemoryStream(bytes))
            {
                using (Image image = Image.FromStream(originalImageMemoryStream))
                {
                    Font font = new Font("Arial", 20, FontStyle.Italic, GraphicsUnit.Pixel);
                    Color color = Color.LightYellow;
                    Point point = new Point(image.Width / 2, image.Height / 2);
                    SolidBrush brush = new SolidBrush(color);
                    using (Graphics graphics = Graphics.FromImage(image))
                    {
                        StringFormat stringFormat = new StringFormat();
                        stringFormat.Alignment = StringAlignment.Center;
                        stringFormat.LineAlignment = StringAlignment.Center;
                        graphics.DrawString("Watermark Text", font, brush, point, stringFormat);
                    }

                    using (MemoryStream updatedImageMemorySteam = new MemoryStream())
                    {
                        image.Save(updatedImageMemorySteam, System.Drawing.Imaging.ImageFormat.Jpeg);
                        convertedToBytes = updatedImageMemorySteam.ToArray();
                    }
                }
            }

            return convertedToBytes;
        }

July 15, 2020 - Posted by | C#.NET, Watermark

No comments yet.

Leave a comment