上传图片添加水印

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

后台代码:

 
        ///
        /// 上传图片
        ///
        ///文件
        ///保存的文件夹名称
        [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();
}

 

posted @ 2018-09-26 10:17  keke..lele  阅读(2171)  评论(3编辑  收藏  举报