MVC 上传图片,裁剪头像

最近在做一个网站用户上传头像(可裁剪)功能,整理成文,如下:

1、选择插件,引用JS

(1)选上传图片的插件:我用的是=> fileupload ,网上下载包里面会有很多文件,这边引用了3个文件(最重要的 jquery 记得引)

jquery.iframe-transport.js

jquery.ui.widget.js

jquery.fileupload.js

(2)截取图片 cutpic.js

2、写前台上传图片 AJAX 语句

<input type="file" id="fileupload" name="files[]" multiple style="position: absolute; opacity: 0; -ms-filter: 'alpha(opacity=0)'; font-size: 1px;direction: ltr;cursor: pointer;margin-left: -50px;width: 100px; direction: ltr; cursor: pointer;">

$(function () {
    $("#tripMsg").hide();
    $("#removeMsgerror").hide();
    $("#fileupload").fileupload({
        url: "/FileUpload/UploadThumbImg",//后台操作路径
        dataType: 'json',
        add: function (e, data) {
            $("#removeMsgerror").hide();
            data.submit();
        },
        done: function (e, data) {
            //done方法就是上传完毕的回调函数
            //注意result要和jquery的ajax的data参数区分,这个对象包含了整个请求信息  
            //返回的数据在result.result中,假设我们服务器返回了一个json对象  
            var res = data.result;
            
            if (res.Success) {
               //上传好图片只有做的一些操作
                    ShowImg(res.ShowImage, result[1], result[2]);       //在截图区显示
                }
            }
            else {
                $("#hidErr").val()
                alert(res.Message);
            }
        }
//移动要裁剪图片的区域之后点保存的操作
$("#btnSave").click(function () {
        $.ajax({
            type: "POST",
            url: "/FileUpload/UploadImg",
            data: { imgUrl: $('#hidImageUrl').val(), pointX: $("#x").val(), pointY: $("#y").val(), maxVal: $("#maxVal").val() },
            success: function (msg) {
                if (msg.Success) {
                 
                }
                else {
                    alert(msg.ReturnData);
                }
            },
            error: function (xhr, msg, e) {
                alert("error");
            }
        });
    });
    });
function ShowImg(imagePath, imgWidth, imgHeight) {
    var imgPath = imagePath != "" ? imagePath : "!images/ef_pic.jpg";
    var ic = new ImgCropper("bgDiv", "dragDiv", imgPath, imgWidth, imgHeight, null);
}

3、后台操作 

传好图片保存,获得截图并保存

public JsonResult UploadThumbImg()
        {
            var CurrentContext = HttpContext;
            // 获取文件流
            var files = CurrentContext.Request.Files;
            
            if (files.Count > 0)
            {

                Stream stream = null;
                System.Drawing.Image originalImg = null;   //原图  
                int minWidth = 94;   //最小宽度
                int minHeight = 94;  //最小高度
                int maxWidth = 300;  //最大宽度
                int maxHeight = 300;  //最大高度
                string imageOfSize = string.Empty;  //返回信息
                try
                {
                    // 文件上传后的保存路径
                    String pathOnServer = Path.Combine(StorageRoot);//StorageRoot 路径,我写的是全局变量,因为很多地方用到
                    string filePath = pathOnServer + "/Users/" + userName.ToLower() + "/" + loginType + "/";
                    string uploadFilePath = filePath;
                    string ext = Path.GetExtension(files[0].FileName).ToLower();   //上传文件的后缀(小写)

                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    string fileName = Path.GetFileName(files[0].FileName);// 原始文件名称
                    string saveName = Guid.NewGuid().ToString() + ext; // 保存文件名称
                    string flag = "/temp" + DateTime.Now.ToFileTime() + ext;
                    if (ext == ".jpg" || ext == ".png")
                    {
                        uploadFilePath += "\\" + flag;   //图文件路径

                        stream = files[0].InputStream;
                        
                        originalImg = System.Drawing.Image.FromStream(stream);

                        if (originalImg.Width >= minWidth && originalImg.Height >= minHeight)
                        {
                            originalImg.Save(uploadFilePath);

                                imageOfSize = "Temp" + "$" + originalImg.Width + "$" + originalImg.Height;
                        }
                        else
                        {
                            return Json(new { Success = false, Message = "Image size must be larger than " + minWidth + "*" + minHeight }, JsonRequestBehavior.AllowGet);//图片尺寸必须大于
                        }
                    }
                    else
                        return Json(new { Success = false, Message = "The image format should be .jpg or .png" }, JsonRequestBehavior.AllowGet);//请输入正确图片格式
                    return Json(new { Success = true, FileName = fileName, SaveName = saveName, ShowImage = UrlBase + "/Users/" + userName.ToLower() + "/" + loginType + "/" + flag, ThumbImgPath = "/Users/" + userName.ToLower() + "/" + loginType + "/" + flag, ImageOfSize = imageOfSize });
                }
                catch (Exception ex)
                {
                    return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
                }
                finally
                {
                    if (originalImg != null)
                    {
                        originalImg.Dispose();
                    }

                    if (stream != null)
                    {
                        stream.Close();
                        stream.Dispose();
                    }


                    GC.Collect();
                }

            }
            else
            {

                return Json(new { Success = false, Message = "Please select the file to upload!" }, JsonRequestBehavior.AllowGet);//请选择要上传的文件!
            }

        }
[HttpPost]
        public JsonResult UploadImg(string pointX, string pointY, string imgUrl, string maxVal)
        {
            //Bitmap bitmap = null;   //按截图区域生成Bitmap
            Image thumbImg = null;      //被截图 
            //Graphics gps = null;    //存绘图对象  
            Image cutImage = null;
            Image finalImg = null;  //最终图片
            string savePath = string.Empty;
            string msg = string.Empty;
            string fileName = string.Empty;
            bool result=true;
            if (!string.IsNullOrEmpty(pointX) && !string.IsNullOrEmpty(pointY) && !string.IsNullOrEmpty(imgUrl))
            {
                try
                {
                    int finalWidth = 94;
                    int finalHeight = 94;
                    var userName = Request.Cookies["userName"].Value;
                    var loginType = Request.Cookies["loginType"].Value;
                    ClientSiteUser cMod = bll.GetClientUserById(userName);
                    int X = Convert.ToInt32(pointX);
                    int Y = Convert.ToInt32(pointY);
                    string ext = System.IO.Path.GetExtension(imgUrl).ToLower();   //上传文件的后缀(小写)
                    string pathOnServer = Path.Combine(StorageRoot);
                    string documentUrl = "/Users/" + userName.ToLower() + "/" + loginType;//存放文件夹
                    string docStr = pathOnServer + documentUrl;//上传路径
                    if (!string.IsNullOrWhiteSpace(userName) && cMod != null)
                    {
                        //获取截图 1、创建画布 
                        //bitmap = new System.Drawing.Bitmap(Convert.ToInt32(maxVal), Convert.ToInt32(maxVal));
                        thumbImg = System.Drawing.Image.FromFile(pathOnServer + imgUrl);
                        //System.Drawing.Rectangle rl = new System.Drawing.Rectangle(Convert.ToInt32(pointX), Convert.ToInt32(pointY), Convert.ToInt32(maxVal), Convert.ToInt32(maxVal));   //得到截图矩形

                        //gps = System.Drawing.Graphics.FromImage(bitmap);
                         在指定位置并且按指定大小绘制指定的 Image 的指定部分,获得到截图 
                        //gps.DrawImage(thumbImg, 0, 0, rl, System.Drawing.GraphicsUnit.Pixel);
                        
                        cutImage = GetCutImage(Convert.ToInt32(pointX), Convert.ToInt32(pointY), thumbImg, Convert.ToInt32(maxVal));
                        //截图等比例缩放得到最终图片
                        finalImg = GetThumbImage(cutImage, finalWidth, finalHeight);
                        fileName = "/Img" + DateTime.Now.ToFileTime() + ext;
                        savePath = docStr + fileName;

                        if (!string.IsNullOrWhiteSpace(cMod.UrlOfAvatarPicture))
                        {
                            FileDel(cMod.UrlOfAvatarPicture);
                        }
                        msg = UrlBase + documentUrl + fileName;
                        cMod.UrlOfAvatarPicture = documentUrl + fileName;
                        //将图片路径保存至数据库
                        if (bll.UpdateUrlOfAvatarPicture(cMod))
                        {
                            if (!System.IO.Directory.Exists(docStr))
                            {
                                System.IO.Directory.CreateDirectory(docStr);
                            }
                            finalImg.Save(savePath);
                        }
                        else result = false;
                        //显示释放资源 
                        //bitmap.Dispose();
                        thumbImg.Dispose();
                        //gps.Dispose();
                        cutImage.Dispose();
                        finalImg.Dispose();
                        GC.Collect();
                        FileDel(imgUrl);
                    }
                }
                catch (Exception ex)
                {
                    result = false;
                    msg = ex.Message;
                }

            }
            return Json(new { Success = result,ReturnData=msg });
        }
 ///<summary>
        /// 裁剪图片
        ///</summary>
        ///<param name="originalImage">原始图片</param>
        ///<param name="thumMaxWidth">裁剪后需要显示的宽度</param>
        ///<param name="thumMaxHeight">裁剪后需要显示的高度</param>
        ///<returns>返回裁剪后的Image对象</returns>
        public static System.Drawing.Image GetThumbImage(Image originalImage, int thumMaxWidth, int thumMaxHeight)
        {
            Image newImage = originalImage;
            Graphics graphics = null;
            try
            {
                // 创建画布
                newImage = new Bitmap(originalImage.Width, originalImage.Height);
                graphics = Graphics.FromImage(newImage);
                // 指定高质量、低速度呈现。
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                // 用白色清空 
                graphics.Clear(System.Drawing.Color.Transparent);
                // 在指定位置并且按指定大小绘制指定的 Image 的指定部分。 
                graphics.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, thumRealSize.Width, thumRealSize.Height), new System.Drawing.Rectangle(0, 0, originalImage.Width, originalImage.Height), System.Drawing.GraphicsUnit.Pixel);
            }
            catch { }
            finally
            {
                if (graphics != null)
                {
                    //显示释放资源 
                    graphics.Dispose();
                    graphics = null;
                }
            }
            return newImage;
        }

上传成功显示到裁剪区

 裁剪保存成功,右上角是裁剪后的图片

 

参考自:https://www.cnblogs.com/wifi/articles/2573131.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值