欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

上传图片添加水印

程序员文章站 2023-01-19 09:30:28
由于项目需要,所以写了下面一段添加水印的代码,如下: 后台代码: /// /// 上传图片 /// ///文件 ///保存的文件夹名称 [HttpPost] public ActionResult UpLoadingImg(HttpPostedFileBase upfile, string file ......

  由于项目需要,所以写了下面一段添加水印的代码,如下:

后台代码:

 
        ///
        /// 上传图片
        ///
        ///文件
        ///保存的文件夹名称
        [httppost]
        public actionresult uploadingimg(httppostedfilebase upfile, string filepath)
        {
            //判断文件是否存在
            if (upfile == null && upfile.contentlength <= 0)
                return error("文件不正确,请重新上传!");
            var path = appdomain.currentdomain.setupinformation.applicationbase;
            filepath = string.isnullorempty(filepath) ? "unknow" : filepath;
            //返回图片相对地址
            var returnpath = $"{filepath}/{datetime.now.tostring("yyy-mm")}";
            filepath = $"uploadimages\\{filepath}";
            path = $"{path}{filepath}\\{datetime.now.tostring("yyy-mm")}";

            if (!system.io.directory.exists(path))
            {
                system.io.directory.createdirectory(path);//不存在就创建目录
            }
            //验证图片格式是否正确
            string type = upfile.filename.trim().substring(upfile.filename.lastindexof(".") + 1);
            var directory = path;
            path = $"{path}\\{datetime.now.tostring("dd-hh-mm-ss")}.{type}";
            returnpath = $"{returnpath}/{datetime.now.tostring("dd-hh-mm-ss")}water.{type}";
            if (type == "bmp" || type == "jpg" || type == "jpg" || type == "bmp" || type == "png" || type == "png")
            {
                upfile.saveas(path);
                //保存水印图片
                image img = image.fromfile(path);
                addwatermarkandsave(directory, $"{datetime.now.tostring("dd-hh-mm-ss")}water.{type}", "房屋管理", img, color.darkgray);
            }
            else
            {
                return error("文件格式错误!");
            }
            return success(returnpath);
        }

 
        ///
        /// 图片加文字水印
        ///
        ///
        ///水印文字,如果是多行用分号隔开
        ///图片
        ///文字颜色
        ///保存地址
        /// 
        private bool addwatermarkandsave(string path, string filename, string text, image img,
                     color textcolor)
        {
            try
            {
                if (!directory.exists(path))
                {
                    directory.createdirectory(path);
                }
                var paddingleft = 1;
                var paddingtop = 1;
                var textfont = new font("宋体", 19.0f);
                bitmap bm = new bitmap(img);
                system.drawing.graphics graphics = system.drawing.graphics.fromimage(bm);
                system.drawing.brush brush = new solidbrush(textcolor);
                var leftlength = (img.width - paddingleft) / 300;
                leftlength = leftlength == 0 ? 1 : leftlength;
                char[] str = text.tochararray();
                for (var j = 0; j < leftlength; j++)
                {
                    var left = paddingleft + 300 * j;
                    var top = paddingtop + 300 * j;
                    for (int i = 0; i < str.length; i++)
                    {
                        graphics.drawstring(str[i].tostring(), textfont, brush, left + 30 * i, top + 33 * i);
                    }
                }
                graphics.dispose();
                bm.save($"{path}\\{filename}", imageformat.jpeg);
                bm.dispose();
                return true;
            }
            catch (exception e)
            {
            }
            return true;
        }
   
  

 

前端代码示例:

  
<input name="url" type="file" class="upload_input" style="display: none;" onchange="preview(this)">
<div class="preview" id="houseimgtypeherf"></div>
<div class="click" onclick="loadimg(this)"></div>
<div class="delete" onclick="deleteimg(this)">
  <svg class="icon" aria-hidden="true">
     <use xlink:href="#icon-shanchu4"></use>
  </svg>
</div>
 

 

 

 

js代码:注:其中“imghed”为后端传递的图片前缀

function getimgsrc(imgsrc) {
        var formdata = new formdata();
        formdata.append("filepath", "shop");
        formdata.append('upfile', imgsrc);
        var url = "../../common/uploadingimg";
        $.ajax({
            url: url,
            type: 'post',
            data: formdata,
            contenttype: false,
            processdata: false,
            success: function (res) {
                addimgsrc(res.message)
            }, error(err) {
                console.log(err);
            }
        })
    }
    function addimgsrc(src) {
        prevdiv.html('<img src="' + imagehead + '' + src + '"  data-id="' + src + '" alt="图片" />');
    }

  function preview(file) {
    var prevdiv = $(file).parent().find('.preview');
    var id = prevdiv.attr("id");
    var imagehead = $("#imgheadres").val();
    if (file.files && file.files[0]) {
        var reader = new filereader();
        reader.onload = function(evt) {
            var imgsrc = evt.target.result;
            getimgsrc(file.files[0])
        }
        reader.readasdataurl(file.files[0]);
    } else {//ie
    }
    $(file).parent().find('.delete').show();
}