Watermark background image in ASP.NET 5

Last modified: June 17, 2021

In my previous blog, I talked about how to upload files to the Microsoft SQL Server database. It is very common for a web application to have watermark the image to protect or copyright them. In this tutorial, we will extend upload files to the database by watermarking the images.

Step 1

Download the project "upload files to the Microsoft SQL Server database" source code from here. We are going to re-use the code from it. Open the solution.

Step 2

We are going to install a Nuget package that will allow us to watermark the image. Right-click on the solution and click "Manage Nuget Package", search for System.Drawing.Common and install it.


Step 3

We first check if the file has any content (line 4). Then we create a memorystream and copy the upload file to it (line 6-7). After that, we convert MemoryStream into an Image variable (line 10). In line 12, We then create a graphic variable from the image variable. We create a font, color, brush, point for watermark text. We then set watermark text "kafle.io" and assign font, brush, and point variables. You can set these properties as your need. Finally in line 21, we create another MemoryStream and save the image variable to it. Finally, we add it to newFile object and save it to the database.

[HttpPost] public async Task UploadFile(IFormFile file) { if (file.Length > 0) { using (var stream = new MemoryStream()) { await file.CopyToAsync(stream); using (var image = Image.FromStream(stream)) { using (var graphic = Graphics.FromImage(image)) { var font = new Font(FontFamily.GenericMonospace, 40, FontStyle.Regular, GraphicsUnit.Pixel); var color = Color.FromArgb(255, 255, 0, 0); var brush = new SolidBrush(color); var point = new Point(image.Width - 120, image.Height - 30); graphic.DrawString("kafle.io", font, brush, point); // will water mark "kafle.io" on the images. using (MemoryStream m = new MemoryStream()) { image.Save(m, image.RawFormat); var newFile = new Models.File(); newFile.MimeType = file.ContentType; newFile.FileName = Path.GetFileName(file.FileName); newFile.Content = m.ToArray(); await _fileService.AddFile(newFile); } } } } } Response.Redirect("/File"); }