Show image with watermark dynamic using code

  ASP.NET Projects

Step 1: Call the page where you code for image merging :

Step 2:  Add the below code in code behind:-


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


protected void Page_Load(object sender, EventArgs e)
{

string ThumbnailPath = Server.MapPath(@"images/testimage.jpg");
string watermark =Server.MapPath(@"images/watermark.png");
drawimagewm(ThumbnailPath, watermark, 50, 50);


}
public void drawimage(string imageurl, string watermark, int startx, int starty)
{
    string ThumbnailPath = imageurl;
    string Thumb_WMPath = watermark;

    System.Drawing.Image image = System.Drawing.Image.FromFile(ThumbnailPath);
    System.Drawing.Image img_WM = System.Drawing.Image.FromFile(Thumb_WMPath);

    int width = image.Width;
    int height = image.Height;

    int width2 = img_WM.Width;
    int height2 = img_WM.Height;

    System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(image);

    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphics.SmoothingMode = SmoothingMode.HighQuality;
    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphics.CompositingQuality = CompositingQuality.HighQuality;

    if (startx > (width - width2) || starty > (height - (height2)))
    {
        graphics.DrawImage(image2, new Point(startx, starty));
    }
// I use 50 for gapping between two watermark...
    for (int i = startx; i < (width - (width2)); i = i + width2 + 50)
    {
        for (int j = starty; j < (height - (height2)); j = j + height2 + 50)
        {
            graphics.DrawImage(img_WM, new Point(i, j));
        }
    }
    ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
    EncoderParameters encoderParameters;
    encoderParameters = new EncoderParameters(1);
    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

    string sExt = System.IO.Path.GetExtension(ThumbnailPath);
    Response.ContentType = "image/jpeg";

    if (sExt.ToString() == ".jpg" || sExt.ToString() == ".jpeg")
    {
        image.Save(Response.OutputStream, info[1], encoderParameters);
    }
    else
    {
        image.Save(Response.OutputStream, image.RawFormat);
    }
    image.Dispose();
    img_WM.Dispose();
}

 

51 thoughts on - Show image with watermark dynamic using code

LEAVE A COMMENT