【问题标题】:How to add watermark logo while uploading an image in mvc如何在mvc中上传图片时添加水印标志
【发布时间】:2021-02-10 23:33:31
【问题描述】:

如何在asp.net mvc中上传图片时添加水印图片。 我正在使用 jquery.uploadfile.min.js 多个文件上传来上传图像。 想要添加自动存储的徽标图像(水印)以附加到我要上传的图像文件中。

在视图中:

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();   
    });
});

在处理程序中:

    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);
        }
    }

【问题讨论】:

  • 没问题。我刚刚在谷歌上搜索了“c# add watermark to image”。从搜索结果中,您可能还可以遵循许多其他指南。你自己做过研究吗?
  • 我用谷歌搜索但找不到任何合适的解决方案,实际上我在上传图片时得到了添加水印文本的结果,但我希望水印图片附加到我的图片中。没问题 ADyson :) 再次感谢!祝你有美好的一天。
  • @ADyson using (Graphics imageGraphics = Graphics.FromImage(image)) 这一行给出内存不足异常。

标签: c# asp.net-mvc


【解决方案1】:

请参考下面的代码来添加水印标志。

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");
    }

【讨论】:

  • 欢迎,没有问题。
【解决方案2】:

我已经安装并尝试了您的 dll。一切都很好,只有一个问题。水印文本垂直添加到垂直图像(高度大于宽度的图像)。更好的解决方案是在垂直图像和水平图像中添加水平线中的水印。不管怎么说,还是要谢谢你。

--编辑--

我已经解决了这段代码中的问题,它检查并更改了需要的图像的方向。 (uploadedImage 是我从流中读取的图像)

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
    }
}

【讨论】:

    【解决方案3】:

    最近我发布了一个 nugget 包,它可以添加图像水印,并控制不透明度和放置水印的目标点。此外,您还可以添加文本水印并进行图像裁剪/调整大小。

    通过金块安装:

    Install-Package LazZiya.ImageResize

    那么你可以使用如下代码:

    //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();
    

    [更新]

    包更新,修改了一些方法,更好的支持更多图片格式(包括gif动画)。

    更多详情请见the docs

    live demo page

    【讨论】:

    • 已经有很多图像库可用,为什么还要创建另一个?另外,为什么要使用 System.Drawing?
    • 为什么是另一个库?就像为什么另一个操作系统一样?为什么另一辆车?为什么另一个产品具有相似但具有竞争力的功能? System.Drawing 用于访问Image 类。
    • 与其他更旧、测试更好、功能更丰富、维护更积极的图像处理库相比,我没有看到有竞争力的功能。您知道 System.Drawing 的问题吗?参见例如hanselman.com/blog/HowDoYouUseSystemDrawingInNETCore.aspx
    • 是的,我知道这个问题,我也知道其余的库。但这并不意味着我必须放弃或永远不要重新开始。替代品将一直存在。
    • 顺便说一句,我正在使用 System.Drawing.Common 由 Microsoft 维护的用于 .NET Core 的 System.Drawing 实现。
    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    相关资源
    最近更新 更多