0

How to add watermark image while uploading image in asp.net mvc. I am using jquery.uploadfile.min.js multiple file upload for uploading image. Want to add automatically stored logo image (watermark) to append in my image file that i am going to upload.

IN VIEW:

var errorOccured = false;
$(function () {
    var uploadObj = $("#multipleupload").uploadFile({
        url: "./Handler.ashx",
        multiple: true,
        fileName: "myfile",
        maxFileSize: 1024 * 5000,
        allowedTypes: "jpg,jpeg,gif,png",
        autoSubmit: false,
        formData: { "FunctionName": "UploadProductImage", "ProductID": '@clsEncrypt.Encrypt(ViewBag.ProductID.ToString())' }, //"ImgResizeOption": ImgResizeOption
        afterUploadAll: function () {
            if (!errorOccured) {
                window.location.href = 'ProductImage?Product=@(clsEncrypt.Encrypt(ViewBag.ProductID.ToString()))';
            }
        },
        onError: function (files, status, errMsg) {
            alert('file(s) could not be uploaded. Error: ' + errMsg);
            errorOccured = true;
        }
    });

    $("#startUpload").click(function () {
        uploadObj.startUpload();   
    });
});

IN HANDLER :

    public void UploadProductImage()
    {
        int ProductID = Convert.ToInt32(clsEncrypt.Decrypt(HttpContext.Current.Request["ProductID"]));
        string PhysicalFolderPath = "~/Images/Product/";

        for (int j = 0; j < HttpContext.Current.Request.Files.Count; j++)
        {
            HttpPostedFile uploadFile = HttpContext.Current.Request.Files[j];
            string extention = System.IO.Path.GetExtension(uploadFile.FileName);
            UploadPic(uploadFile, j++, PhysicalFolderPath, ProductID);
        }
    }

    protected void UploadPic(HttpPostedFile FUPhoto, int sort, string RemotePath, int ProductID)
    {
        if (FUPhoto.FileName != "")
        {
            string ImgUploadResponse = "";
            string strExt = Path.GetExtension(FUPhoto.FileName).Trim().ToLower();
            string ImageName = DateTime.Now.ToFileTimeUtc() + strExt;
            string OriginalImageFullPath = "~/Images/Product/" + ImageName;
            if (Directory.Exists(HttpContext.Current.Server.MapPath("~/Images/Product/")).Equals(false))
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Images/Product/"));
            FUPhoto.SaveAs(HttpContext.Current.Server.MapPath(OriginalImageFullPath));

            ProductImageEntity objProdImage = new ProductImageEntity();
            objProdImage.ProductID = ProductID;
            if (ImgUploadResponse != "")
                objProdImage.Image = "";
            else
                objProdImage.Image = ImageName;
            if (!String.IsNullOrEmpty(objProdImage.Image))
                new ProductImageBLL().InsertUpdateProductImage(objProdImage);
        }
    }
  • https://stackoverflow.com/questions/12870137/automatically-add-watermark-to-an-image – ADyson Jul 08 '19 at 11:07
  • No problem. I just googled "c# add watermark to image". There are probably many other guides you could follow too, from the search results. Did you do any research of your own? – ADyson Jul 08 '19 at 12:11
  • I googled it but couldn't found any proper solution, actually i was getting result of adding watermark text while uploading image, But i wanted watermark image to append in my picture. No problem ADyson :) Thanks again ! Have a good day. – whoviralmistry Jul 08 '19 at 12:21
  • @ADyson using (Graphics imageGraphics = Graphics.FromImage(image)) this line giving out of memory exception. – whoviralmistry Jul 18 '19 at 10:24

3 Answers3

1

Please refer the below code for watermark logo to add from code side.

using (Image image = Image.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"))
    using (Image watermarkImage = Image.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\watermark.png"))
    using (Graphics imageGraphics = Graphics.FromImage(image))
    using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
    {
        int x = (image.Width / 2 - watermarkImage.Width / 2);
        int y = (image.Height / 2 - watermarkImage.Height / 2);
        watermarkBrush.TranslateTransform(x, y);
        imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width+1, watermarkImage.Height)));
        image.Save(@"C:\Users\Public\Pictures\Sample Pictures\Desert_watermark.jpg");
    }
Hitesh Gohel
  • 117
  • 4
0

Recently I've published a nugget package that do add image water mark with control over opacity and target spot to place the watermark in. Additionally you can add text watermark and do image crop/resize as well.

install via nugget:

Install-Package LazZiya.ImageResize

then you can use the code as below:

//get image from local path
var img = Image.FromFile("wwwroot\\images\\lum3n-358833-unsplash.jpg");

//scale and crop, 600x250 center focus 
var newImg = ImageResize.ScaleAndCrop(img, 600, 250, TargetSpot.Center);

//watermark image path
var imgWatermark = "wwwroot\\images\\icon.png";

//add image watermark
newImg.ImageWatermark(imgWatermark, 
                TargetSpot.TopRight, //define target spot
                10,                  //margin
                37);                 //opacity (0-100)

//save new image
newImg.SaveAs("wwwroot\\images\\600x250-image-watermark.jpg");

//dispose to free up memory
img.Dispose();
newImg.Dispose();

[UPDATE]

The package is updated and some methods has been changed, and better support for more image formats is available (including animated gif).

See the docs for more details.

see live demo page.

LazZiya
  • 5,286
  • 2
  • 24
  • 37
  • 1
    There are already plenty of imaging libraries available, why create yet another? Also, why use System.Drawing? – CodeCaster Jul 08 '19 at 12:43
  • 1
    Why another library? same like why another OS? why another car? why another product with similar but competitive features? `System.Drawing` used to access `Image` class. – LazZiya Jul 08 '19 at 12:51
  • I don't see competitive features compared to other, older, better tested, more feature-rich, more actively maintained image processing libraries. You do know about the trouble with System.Drawing? See for example https://www.hanselman.com/blog/HowDoYouUseSystemDrawingInNETCore.aspx. – CodeCaster Jul 08 '19 at 13:10
  • 1
    Yes I'm aware of this issue, and I know the rest of the libraries as well. But this doesn't mean that I have to give-up or never do a fresh start. Alternatives will exist all the time. – LazZiya Jul 08 '19 at 13:30
  • btw, I'm using `System.Drawing.Common` the Microsoft-maintained implementation of `System.Drawing` for .NET Core. – LazZiya Jul 08 '19 at 13:54
0

I have installed and tried your dll. Everything is good but one issue. The watermark text is added vertically to vertical images (images whose height is bigger than width). Better solution is to add watermark in a horizantal line to vertical images as well as horizantal images. Thanks anyway.

--Edit--

I have solved the problem within this code, which checks and changes the orientation of the image in need. (uploadedImage is the image that i read from stream)

if (uploadedImage.PropertyIdList.Contains(0x0112))
{
    PropertyItem propOrientation = uploadedImage.GetPropertyItem(0x0112);
    short orientation = BitConverter.ToInt16(propOrientation.Value, 0);
    if (orientation == 6)
    {
        uploadedImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
    }
    else if (orientation == 8)
    {
        uploadedImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
    }
    else
    {
        // Do nothing
    }
}
Milo
  • 3,365
  • 9
  • 30
  • 44