How to add Watermark Text on Image in ASP.Net c#

In this article, we will make a copyright text on image in asp.net c#

Source Code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="watermarkonuploadimage.aspx.cs" Inherits="watermarkonuploadimage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">

        <fieldset style="width: 300px">

            <legend>Add Watermark Text on Upload Image  </legend>
           
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <br /><br />
            <asp:Button ID="btnupload" Text="Upload" runat="server" OnClick="btnupload_Click" />
        </fieldset>

    </form>
</body>
</html>

Code behind(C#):-

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class watermarkonuploadimage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnupload_Click(object sender, EventArgs e)
    {
        string watermarkText = "© www.neerajcodesolutions.com";

       
        string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName) + ".png";

       
        using (Bitmap bmp = new Bitmap(FileUpload1.PostedFile.InputStream, false))
        {
            using (Graphics grp = Graphics.FromImage(bmp))
            {
                Brush brush = new SolidBrush(Color.Red);
                Font font = new System.Drawing.Font("Arial", 40, FontStyle.Bold, GraphicsUnit.Pixel);
                SizeF textSize = new SizeF();
                textSize = grp.MeasureString(watermarkText, font);
                Point position = new Point((bmp.Width - ((int)textSize.Width + 10)), (bmp.Height - ((int)textSize.Height + 10)));
                grp.DrawString(watermarkText, font, brush, position);

                using (MemoryStream memoryStream = new MemoryStream())

                {
                    bmp.Save(memoryStream, ImageFormat.Png);
                    memoryStream.Position = 0;
                    Response.Clear();
                    Response.ContentType = "image/png";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                    memoryStream.WriteTo(Response.OutputStream);
                    Response.Flush();
                    Response.Close();
                    Response.End();
                }
            }
        }
    }
}

Out-put:-
How to add Watermark Text on Image in ASP.Net c# How to add Watermark Text on Image in ASP.Net c# Reviewed by NEERAJ SRIVASTAVA on 9:31:00 PM Rating: 5

No comments:

Powered by Blogger.