Asp net adding watermark to images on the fly

Introduction

Adding a to images on the fly is a common in web development. In ASP.NET, there are several ways to achieve this. In this article, we will explore one approach using the System. namespace and the Graphics .

Step 1: Setting up the ASP.NET project

Before we dive into the code, let's set up a new ASP.NET project. Open Visual Studio and create a new ASP.NET Web project. Choose the appropriate project template and give it a name.

Step 2: Adding the watermark image

, we need to add the watermark image to our project. Create a new folder called “Images” in the root directory of your project. Copy the watermark image file into this folder.

Step 3: Writing the code

Now, let's write the code to add the watermark to images on the fly. Open the code-behind file of the page where you want to add the watermark.


using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

protected void Page_Load(object sender, EventArgs e)
{
    string imagePath = Server.MapPath("~/Images/original.jpg");
    string watermarkPath = Server.MapPath("~/Images/watermark.png");

    using (Image image = Image.FromFile(imagePath))
    using (Image watermark = Image.FromFile(watermarkPath))
    using (Graphics graphics = Graphics.FromImage(image))
    {
        int x = (image.Width - watermark.Width) / 2;
        int y = (image.Height - watermark.Height) / 2;

        graphics.SmoothingMode = SmoothingMode.AntiAlias;
        graphics.DrawImage(watermark, x, y, watermark.Width, watermark.Height);
    }

    //  the modified image
    using ( memoryStream = new MemoryStream())
    {
        image.Save(memoryStream, ImageFormat.Jpeg);
        Response.ContentType = "image/jpeg";
        memoryStream.WriteTo(Response.OutputStream);
    }
}

Step 4: the solution

Now that we have written the code, let's test our solution. Run the project and navigate to the page where you added the code. The original image should be displayed with the watermark applied.

Conclusion

Adding a watermark to images on the fly in ASP.NET can be achieved using the System.Drawing namespace and the Graphics class. By the steps outlined in this article, you can easily implement this functionality in your ASP.NET projects.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents