基于Layui + .net mvc 上传图片压缩并添加水印

html

                <button type="button" class="layui-btn layui-btn-sm" id="图片上传">图片上传</button>

js

/*文件上传方法*/
layui.use('upload', function () {
    var $ = layui.jquery
        , upload = layui.upload
        , form = layui.form;
    upload.render({
        elem: '#图片上传'//附件上传按钮ID
        , url: '/tool/upload(附件上传后台地址)'
        , multiple: true
        , accept: 'file'
        , exts: 'jpg|jpeg|gif|bmp|png|pjpeg'//允许的类别
        , before: function (obj) {/*上传前执行的部分*/ }
        , done: function (res) {/*上传后执行的部分*/ }
        , allDone: function (res) {/*全部文件上传完毕执行该方法*/ }
    });
});

Controller

using System;
using System.Drawing;
using System.Web.Mvc;

namespace SFMVC3._0.Controllers
{
    public class toolsController : Controller
    {
        public string upload(FormCollection fc)
        {
            try
            {
                string guid = Guid.NewGuid().ToString();
                var file = Request.Files[0];
                if (file == null ||
                  String.IsNullOrEmpty(file.FileName) ||
                  file.ContentLength == 0)
                {
                    return "{\"code\":1,\"msg\":\"文件上传失败!\" ,\"data\":{\"src\":\"\"}}";
                }

                string filename = System.IO.Path.GetFileName(file.FileName);
                string newName = buildFileName(guid, filename);
                string virtualPath = String.Format("/upload/{0}", newName);

                string path = Server.MapPath(virtualPath);

                string prefix = System.IO.Path.GetExtension(filename).ToLower();
                System.Drawing.Image water = System.Drawing.Image.FromFile(Request.MapPath("/images/watermark.png"));//图片水印位置
                MakeThumbnai(file.InputStream, path, 1024, 0, prefix, water);

                return "{\"code\":0,\"msg\":\"文件上传成功!\" ,\"data\":{\"src\":\"\",\"filename\":\"" + filename + "\",\"newname\":\"" + newName + "\",\"size\":\"" + (file.ContentLength / 1024) + "\"}}";
            }
            catch (Exception ex)
            {
                return "{\"code\":1,\"msg\":\"文件上传失败!\" ,\"data\":{\"src\":\"\"}}";
            }
        }
        /// <summary>
        /// 根据文件名称生产新的文件名称;
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static string buildFileName(string newname, string filename)
        {
            string postfix = filename.Substring(filename.LastIndexOf('.'));
            string newName = newname + postfix;

            return newName;
        }
        /// <summary>
        /// 图片压缩方法
        /// </summary>
        /// <param name="PicStream">图片</param>
        /// <param name="thumbnailPath">文件路径</param>
        /// <param name="width">指定宽,不可为0</param>
        /// <param name="height">指定高,为0时根据宽自动适应</param>
        /// <param name="PicExtension">图片格式</param>
        /// <param name="water"></param>
        public static void MakeThumbnai(System.IO.Stream PicStream, string thumbnailPath, int width, int height, string PicExtension, Image water)
        {

            System.Drawing.Image originalImage = System.Drawing.Image.FromStream(PicStream);//打开文件流
            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            toheight = originalImage.Height * width / originalImage.Width;


            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);

            Watermark(bitmap, water);//添加水印的方法
            try
            {
                //根据原来的图片格式,保存为原图片格式
                switch (PicExtension.ToLower())
                {
                    case "jpg":
                        //以jpg格式保存缩略图
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;
                    case "jpeg":
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;
                    case "pjpeg":
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;
                    case "gif":
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif);
                        break;
                    case "bmp":
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp);
                        break;
                    case "png":
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
                        break;
                    default:
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;
                }

            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        /// <summary>
        /// 添加水印的方法
        /// </summary>
        /// <param name="img">需要添加水印的图片</param>
        /// <param name="water">水印,文字水印可以改成字符串</param>
        private static void Watermark(Image img, Image water)
        {
            Graphics graphics = Graphics.FromImage(img);

            graphics.DrawImage(water, new Rectangle(img.Width - water.Width, 0, water.Width, water.Height), 0, 0, water.Width, water.Height, GraphicsUnit.Pixel);
        }
    }
}

 

上一篇:openTSDB详解之 Put


下一篇:openTSDB详解之Definitions