C# 批量上传文件 添加图片水印

<form action="/Employees/BatchUpload" class="dropzone"
      enctype="multipart/form-data"
      id="my-dropzone"
      name="photoFile"
      method="post" style="margin-top: 45px;"><!--上传图片时,需要同时提交的数据,这里做个演示-->
    @Html.Hidden("hidAlbumId")
</form>
<div>
    <!--上传按钮,提供多张图片一次性上传的功能-->
    <button type="submit" name="photoFile" id="submit-all" disabled="disabled">上传</button>
</div>
<script>
            //Dropzone的初始化,myDropzone为form的id
            Dropzone.options.myDropzone = {
            //指定上传图片的路径
            //url: "@Url.Action("BatchUpload", "Employees")",
            //添加上传取消和删除预览图片的链接,默认不添加
            addRemoveLinks: true,
            //关闭自动上传功能,默认会true会自动上传//也就是添加一张图片向服务器发送一次请求
            autoProcessQueue: false,
            //允许上传多个照片
            uploadMultiple: true,
            //每次上传的最多文件数,经测试默认为2,坑啊
            //记得修改web.config 限制上传文件大小的节
            parallelUploads: 100,
            init: function () {
                var submitButton = document.querySelector("#submit-all")
                myDropzone = this; // closure
                //为上传按钮添加点击事件
                submitButton.addEventListener("click", function () {
                    //手动上传所有图片
                    myDropzone.processQueue();
                });
                //当添加图片后的事件,上传按钮恢复可用
                this.on("addedfile", function () {
                    $("#submit-all").removeAttr("disabled");
                });
                //当上传完成后的事件,接受的数据为JSON格式
                this.on("complete", function (data) {
                    if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
                        var res = eval('(' + data.xhr.responseText + ')');
                        var msg;
                        if (res.Result) {
                            msg = "恭喜,已成功上传" + res.Count + "张照片!";
                        }
                        else {
                            msg = "上传失败,失败的原因是:" + res.Message;
                        }
                        $("#message").text(msg);
                        $("#dialog").dialog("open");
                        //window.location.href = '/Employees/Index';
                    }
                });

                //删除图片的事件,当上传的图片为空时,使上传按钮不可用状态
                this.on("removedfile", function () {
                    if (this.getAcceptedFiles().length === 0) {
                        $("#submit-all").attr("disabled", true);
                    }
                });
            }
        };
</script>

不仅仅是上传图片,各种文件都可以,可多选,删除,线框可以根据需要自己调节

后台代码

        /// <summary>
        /// 多文件上传、图片添加水印
        /// </summary>
        /// <param name="model"></param>
        /// <param name="photoFile"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult BatchUpload(AttachmentsInfo model, HttpPostedFileBase photoFile)
        {
            bool isSavedSuccessfully = true;
            int count = 0;
            string msg = "";
            string fileName = "";
            string fileExtension = "";
            string filePath = "";
            try
            {
                string directoryPath = Server.MapPath("~/Content/Files");
                if (!Directory.Exists(directoryPath))
                    Directory.CreateDirectory(directoryPath);

                foreach (string f in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[f];
                    if (file != null && file.ContentLength > 0)
                    {
                        fileName = file.FileName;//获取文件名称
                        fileExtension = Path.GetExtension(fileName);
                        filePath = Path.Combine(directoryPath, fileName);//合成路径
                        //var NewName = Path.GetFileNameWithoutExtension(filePath);//新名称
                        var filePaths = Server.MapPath($"~/Content/Files/{NewName}_1" + fileExtension);//图源路径
                        var fileWaterPath = Server.MapPath($"~/Content/Files/{NewName}" + fileExtension);//保存路径
                        file.SaveAs(filePaths);
                        file.SaveAs(fileWaterPath);//保存文件
               //将图片添加水印 ImageHelper.GenerateTextWatermark(filePaths, fileWaterPath, "水印", 12, "宋体", 9, 80); count++; } } } catch (Exception ex) { msg = ex.Message; isSavedSuccessfully = false; } return Content("<script>window.history.back();location.reload();</script>"); }

ImageHelper

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model
{
    public class ImageHelper
    {
        private static bool _isloadjpegcodec;
        private static ImageCodecInfo _jpegcodec;

        /// <summary>获得当前系统安装的JPEG编码解码器</summary>
        /// <returns></returns>
        public static ImageCodecInfo GetJPEGCodec()
        {
            if (ImageHelper._isloadjpegcodec)
                return ImageHelper._jpegcodec;
            foreach (ImageCodecInfo imageEncoder in ImageCodecInfo.GetImageEncoders())
            {
                if (imageEncoder.MimeType.IndexOf("jpeg") > -1)
                {
                    ImageHelper._jpegcodec = imageEncoder;
                    break;
                }
            }
            ImageHelper._isloadjpegcodec = true;
            return ImageHelper._jpegcodec;
        }

        /// <summary>为指定的图片生成缩略图</summary>
        /// <param name="sourceFilename">图片源文件的完整文件名</param>
        /// <param name="destFilename">缩略图文件的完整文件名</param>
        /// <param name="width">缩略图宽度(px)</param>
        /// <param name="height">缩略图高度(px)</param>
        public static void CreateThumbnail(string sourceFilename, string destFilename, int width, int height)
        {
            Image image1 = Image.FromFile(sourceFilename);
            if (image1.Width <= width && image1.Height <= height)
            {
                File.Copy(sourceFilename, destFilename, true);
                image1.Dispose();
            }
            else
            {
                int width1 = image1.Width;
                int height1 = image1.Height;
                float num = (float)height / (float)height1;
                if ((double)width / (double)width1 < (double)num)
                    num = (float)width / (float)width1;
                width = (int)((double)width1 * (double)num);
                height = (int)((double)height1 * (double)num);
                Image image2 = (Image)new Bitmap(width, height);
                Graphics graphics = Graphics.FromImage(image2);
                graphics.Clear(Color.White);
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.DrawImage(image1, new Rectangle(0, 0, width, height), new Rectangle(0, 0, width1, height1), GraphicsUnit.Pixel);
                EncoderParameters encoderParams = new EncoderParameters();
                EncoderParameter encoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                encoderParams.Param[0] = encoderParameter;
                ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo encoder = (ImageCodecInfo)null;
                for (int index = 0; index < imageEncoders.Length; ++index)
                {
                    if (imageEncoders[index].FormatDescription.Equals("JPEG"))
                    {
                        encoder = imageEncoders[index];
                        break;
                    }
                }
                image2.Save(destFilename, encoder, encoderParams);
                encoderParams.Dispose();
                encoderParameter.Dispose();
                image1.Dispose();
                image2.Dispose();
                graphics.Dispose();
            }
        }

        /// <summary>生成图片水印</summary>
        /// <param name="originalPath">源图路径</param>
        /// <param name="watermarkPath">水印图片路径</param>
        /// <param name="targetPath">保存路径</param>
        /// <param name="position">位置</param>
        /// <param name="opacity">透明度</param>
        /// <param name="quality">质量</param>
        public static void GenerateImageWatermark(string originalPath, string watermarkPath, string targetPath, int position, int opacity, int quality)
        {
            Image image1 = (Image)null;
            Image image2 = (Image)null;
            ImageAttributes imageAttr = (ImageAttributes)null;
            Graphics graphics = (Graphics)null;
            try
            {
                image1 = Image.FromFile(originalPath);
                image2 = (Image)new Bitmap(watermarkPath);
                if (image2.Height >= image1.Height || image2.Width >= image1.Width)
                {
                    image1.Save(targetPath);
                }
                else
                {
                    if (quality < 0 || quality > 100)
                        quality = 80;
                    float num = opacity <= 0 || opacity > 10 ? 0.5f : (float)opacity / 10f;
                    int x = 0;
                    int y = 0;
                    switch (position)
                    {
                        case 1:
                            x = (int)((double)image1.Width * 0.00999999977648258);
                            y = (int)((double)image1.Height * 0.00999999977648258);
                            break;
                        case 2:
                            x = (int)((double)image1.Width * 0.5 - (double)(image2.Width / 2));
                            y = (int)((double)image1.Height * 0.00999999977648258);
                            break;
                        case 3:
                            x = (int)((double)image1.Width * 0.990000009536743 - (double)image2.Width);
                            y = (int)((double)image1.Height * 0.00999999977648258);
                            break;
                        case 4:
                            x = (int)((double)image1.Width * 0.00999999977648258);
                            y = (int)((double)image1.Height * 0.5 - (double)(image2.Height / 2));
                            break;
                        case 5:
                            x = (int)((double)image1.Width * 0.5 - (double)(image2.Width / 2));
                            y = (int)((double)image1.Height * 0.5 - (double)(image2.Height / 2));
                            break;
                        case 6:
                            x = (int)((double)image1.Width * 0.990000009536743 - (double)image2.Width);
                            y = (int)((double)image1.Height * 0.5 - (double)(image2.Height / 2));
                            break;
                        case 7:
                            x = (int)((double)image1.Width * 0.00999999977648258);
                            y = (int)((double)image1.Height * 0.990000009536743 - (double)image2.Height);
                            break;
                        case 8:
                            x = (int)((double)image1.Width * 0.5 - (double)(image2.Width / 2));
                            y = (int)((double)image1.Height * 0.990000009536743 - (double)image2.Height);
                            break;
                        case 9:
                            x = (int)((double)image1.Width * 0.990000009536743 - (double)image2.Width);
                            y = (int)((double)image1.Height * 0.990000009536743 - (double)image2.Height);
                            break;
                    }
                    ColorMap[] map = new ColorMap[1]
                    {
            new ColorMap()
            {
              OldColor = Color.FromArgb((int) byte.MaxValue, 0, (int) byte.MaxValue, 0),
              NewColor = Color.FromArgb(0, 0, 0, 0)
            }
                    };
                    ColorMatrix newColorMatrix = new ColorMatrix(new float[5][]
                    {
            new float[5]{ 1f, 0.0f, 0.0f, 0.0f, 0.0f },
            new float[5]{ 0.0f, 1f, 0.0f, 0.0f, 0.0f },
            new float[5]{ 0.0f, 0.0f, 1f, 0.0f, 0.0f },
            new float[5]{ 0.0f, 0.0f, 0.0f, num, 0.0f },
            new float[5]{ 0.0f, 0.0f, 0.0f, 0.0f, 1f }
                    });
                    imageAttr = new ImageAttributes();
                    imageAttr.SetRemapTable(map, ColorAdjustType.Bitmap);
                    imageAttr.SetColorMatrix(newColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                    graphics = Graphics.FromImage(image1);
                    graphics.DrawImage(image2, new Rectangle(x, y, image2.Width, image2.Height), 0, 0, image2.Width, image2.Height, GraphicsUnit.Pixel, imageAttr);
                    EncoderParameters encoderParams = new EncoderParameters();
                    encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, new long[1]
                    {
            (long) quality
                    });
                    if (ImageHelper.GetJPEGCodec() != null)
                        image1.Save(targetPath, ImageHelper._jpegcodec, encoderParams);
                    else
                        image1.Save(targetPath);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (graphics != null)
                    graphics.Dispose();
                if (imageAttr != null)
                    imageAttr.Dispose();
                if (image2 != null)
                    image2.Dispose();
                if (image1 != null)
                    image1.Dispose();
            }
        }

        /// <summary>生成文字水印</summary>
        /// <param name="originalPath">源图路径</param>
        /// <param name="targetPath">保存路径</param>
        /// <param name="text">水印文字</param>
        /// <param name="textSize">文字大小</param>
        /// <param name="textFont">文字字体</param>
        /// <param name="position">位置</param>
        /// <param name="quality">质量</param>
        public static void GenerateTextWatermark(string originalPath, string targetPath, string text, int textSize, string textFont, int position, int quality)
        {
            Image image = (Image)null;
            Graphics graphics = (Graphics)null;
            try
            {
                image = Image.FromFile(originalPath);
                graphics = Graphics.FromImage(image);
                if (quality < 0 || quality > 100)
                    quality = 80;
                Font font = new Font(textFont, (float)textSize, FontStyle.Regular, GraphicsUnit.Pixel);
                SizeF sizeF = graphics.MeasureString(text, font);
                float x = 0.0f;
                float y = 0.0f;
                switch (position)
                {
                    case 1:
                        x = (float)image.Width * 0.01f;
                        y = (float)image.Height * 0.01f;
                        break;
                    case 2:
                        x = (float)((double)image.Width * 0.5 - (double)sizeF.Width / 2.0);
                        y = (float)image.Height * 0.01f;
                        break;
                    case 3:
                        x = (float)image.Width * 0.99f - sizeF.Width;
                        y = (float)image.Height * 0.01f;
                        break;
                    case 4:
                        x = (float)image.Width * 0.01f;
                        y = (float)((double)image.Height * 0.5 - (double)sizeF.Height / 2.0);
                        break;
                    case 5:
                        x = (float)((double)image.Width * 0.5 - (double)sizeF.Width / 2.0);
                        y = (float)((double)image.Height * 0.5 - (double)sizeF.Height / 2.0);
                        break;
                    case 6:
                        x = (float)image.Width * 0.99f - sizeF.Width;
                        y = (float)((double)image.Height * 0.5 - (double)sizeF.Height / 2.0);
                        break;
                    case 7:
                        x = (float)image.Width * 0.01f;
                        y = (float)image.Height * 0.99f - sizeF.Height;
                        break;
                    case 8:
                        x = (float)((double)image.Width * 0.5 - (double)sizeF.Width / 2.0);
                        y = (float)image.Height * 0.99f - sizeF.Height;
                        break;
                    case 9:
                        x = (float)image.Width * 0.99f - sizeF.Width;
                        y = (float)image.Height * 0.99f - sizeF.Height;
                        break;
                }
                graphics.DrawString(text, font, (Brush)new SolidBrush(Color.White), x + 1f, y + 1f);
                graphics.DrawString(text, font, (Brush)new SolidBrush(Color.Black), x, y);
                EncoderParameters encoderParams = new EncoderParameters();
                encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, new long[1]
                {
          (long) quality
                });
                if (ImageHelper.GetJPEGCodec() != null)
                    image.Save(targetPath, ImageHelper._jpegcodec, encoderParams);
                else
                    image.Save(targetPath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (graphics != null)
                    graphics.Dispose();
                if (image != null)
                    image.Dispose();
            }
        }

        /// <summary>生成验证码</summary>
        /// <param name="checkCode"></param>
        /// <returns></returns>
        public static MemoryStream GenerateCheckCode(out string checkCode)
        {
            checkCode = string.Empty;
            ColorTranslator.FromHtml("#1AE61A");
            char[] chArray = new char[27]
            {
        '2',
        '3',
        '4',
        '5',
        '6',
        '8',
        '9',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'J',
        'K',
        'L',
        'M',
        'N',
        'P',
        'R',
        'S',
        'T',
        'W',
        'X',
        'Y'
            };
            Random random1 = new Random();
            for (int index = 0; index < 4; ++index)
                checkCode += (object)chArray[random1.Next(chArray.Length)];
            Bitmap bitmap = new Bitmap(85, 30);
            Graphics graphics = Graphics.FromImage((Image)bitmap);
            Random random2 = new Random(DateTime.Now.Millisecond);
            SolidBrush solidBrush = new SolidBrush(Color.FromArgb(4683611));
            graphics.Clear(ColorTranslator.FromHtml("#EBFDDF"));
            using (StringFormat format = new StringFormat())
            {
                format.Alignment = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;
                format.FormatFlags = StringFormatFlags.NoWrap;
                Matrix matrix = new Matrix();
                float x = -25f;
                float y = 0.0f;
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                for (int index = 0; index < checkCode.Length; ++index)
                {
                    var font = new Font("微软雅黑", 20, FontStyle.Bold | FontStyle.Italic);
                    SizeF sizeF = graphics.MeasureString(checkCode[index].ToString(), font);
                    matrix.RotateAt((float)random2.Next(-15, 10), new PointF(x + sizeF.Width / 2f, y + sizeF.Height / 2f));
                    graphics.Transform = matrix;
                    graphics.DrawString(checkCode[index].ToString(), font, Brushes.Green, new RectangleF(x, y, (float)bitmap.Width, (float)bitmap.Height), format);
                    x += (float)((double)sizeF.Width * 3.0 / 5.0);
                    y += 0.0f;
                    graphics.RotateTransform(0.0f);
                    matrix.Reset();
                    font.Dispose();
                }
            }
            Pen pen = new Pen(Color.Black, 0.0f);
            MemoryStream memoryStream = new MemoryStream();
            try
            {
                bitmap.Save((Stream)memoryStream, ImageFormat.Png);
                return memoryStream;
            }
            finally
            {
                bitmap.Dispose();
                graphics.Dispose();
            }
        }

        public static Font CreateFont(string fontFile, float fontSize, FontStyle fontStyle, GraphicsUnit graphicsUnit, byte gdiCharSet)
        {
            PrivateFontCollection privateFontCollection = new PrivateFontCollection();
            privateFontCollection.AddFontFile(fontFile);
            return new Font(privateFontCollection.Families[0], fontSize, fontStyle, graphicsUnit, gdiCharSet);
        }

        /// <summary>图片格式转换</summary>
        /// <param name="originalImagePath">原始图片地址</param>
        /// <param name="newFormatImagePath">新格式图片地址</param>
        /// <param name="fortmat">待转换的格式</param>
        public static void TranserImageFormat(string originalImagePath, string newFormatImagePath, ImageFormat fortmat)
        {
            new Bitmap(originalImagePath).Save(newFormatImagePath, ImageFormat.Jpeg);
        }

    }
}
View Code

posted @ 2020-07-15 15:27  Hero-韦先生  阅读(312)  评论(0编辑  收藏  举报