博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET MVC4使用JCrop裁剪图片并上传
阅读量:6079 次
发布时间:2019-06-20

本文共 10211 字,大约阅读时间需要 34 分钟。

需要用到的jquery插件 、

百度webuploader插件( )

引用下载好的css和js文件

异步的话还需要引用jquery.form.js文件

布局

@using (Ajax.BeginForm("EditUserHeadPortrait", "Account", null, new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data", id = "form_headportrait" })) { @Html.AntiForgeryToken() @Html.HiddenFor(m => m.HeadPortraitData, new { id = "imgData" }) @Html.Hidden("imgX") @Html.Hidden("imgY") @Html.Hidden("imgW") @Html.Hidden("imgH")
当前头像
设置新头像
支持jpg、jpeg、gif、png或者bmp格式,可以在大照片中裁剪满意的部分。
选 择
预览头像
当前头像
}

js代码

var uploader = new WebUploader.Uploader({    swf: '@Url.Content("~/Scripts/webuploader-0.1.5/Uploader.swf")',    server: '@Url.Action("UploadImage", "FileUpload")',    fileVal: 'imgFile',    formData: { resizeWidth: 300, resizeHeight: 300 },    pick: '#btnBrowserPic', // 选择图片按钮    accept: {        title: 'Images',        extensions: 'gif,jpg,jpeg,bmp,png',        mimeTypes: 'image/.gif,.jpg,.jpeg,.bmp,.png'    },    auto: true, // 自动上传    multiple: false, // 不允许多个文件同时上传    fileNumLimit: 1 // 当前队列数});//开始上传uploader.on("uploadStart", function () {                });//上传成功uploader.on('uploadSuccess', function (file, response) {
  //根据自己返回的结果具体操作   if (response.Status) {           $(".div-origin").html('');           var base64Data = "data:image/bmp;base64," + response.Data;       // 配置 jcrop           $("#imgOrigin").attr("src", base64Data).Jcrop({ onChange: setCoordsAndImgSize, onSelect: setCoordsAndImgSize, aspectRatio: 1, setSelect: [50, 50, 150, 150] }); $("#imgCropped").attr("src", base64Data).css({ width: $(".jcrop-holder").width() + "px", height: $(".jcrop-holder").height() + "px" }); $("#imgData").val(response.Data); }
}); // 上传失败 uploader.on("uploadError", function (file) { alert("图片未加载成功!"); }); // 错误 uploader.on("error", function () {   alert("一次只能上传一张图片(不是有效的图片文件)!"); }); // 上传完成 uploader.on("uploadComplete", function () {   uploader.reset(); // 重置当前队列 }); $("#btn_save").on("click", function () {   $form_headportrait.submit(); }); $form_headportrait.ajaxForm({   dataType: 'json',   success: function (data) {     // 成功后,执行其他操作    }  }); // 纪录裁剪的位置 function setCoordsAndImgSize(e) {
   var imgX = e.x, imgY = e.y, imgW = e.w, imgH = e.h;    $("#imgX").val(imgX);    $("#imgY").val(imgY);    $("#imgW").val(imgW);    $("#imgH").val(imgH);   if (parseInt(e.w) > 0) {
      var rx = 100 / imgW;       var ry = 100 / imgH;       $('#imgCropped').css({
         width: Math.round(rx * $(".jcrop-holder").width()) + 'px',          height: Math.round(ry * $(".jcrop-holder").height()) + 'px',         marginLeft: '-' + Math.round(rx * imgX) + 'px',        marginTop: '-' + Math.round(ry * imgY) + 'px'      }).show();   } }

FileUpload控制器

public class FileUploadController : Controller    {        // GET: FileUpload        [HttpPost]        public ActionResult UploadImage(HttpPostedFileBase imgFile, int? resizeWidth, int? resizeHeight)        {            JsonObject jsonObj = new JsonObject();            if (imgFile != null && imgFile.ContentLength != 0)            {                try                {                    jsonObj.Data = ImageHelper.ResizeImage(imgFile.InputStream, resizeWidth.Value, resizeHeight.Value);                    jsonObj.Status = true;                    jsonObj.Message = "successful";                }                catch (Exception)                {                    jsonObj.Message = "fail";                }            }            return Json(jsonObj, JsonRequestBehavior.AllowGet);        }    }

图片处理类

///     /// 图片处理    ///     public static class ImageHelper    {        public static string CropImage(byte[] content, int x, int y, int cropWidth, int cropHeight)        {            using (MemoryStream stream = new MemoryStream(content))            {                return CropImage(stream, x, y, cropWidth, cropHeight);            }        }        public static string CropImage(Stream content, int x, int y, int cropWidth, int cropHeight)        {            using (Bitmap sourceBitmap = new Bitmap(content))            {                // 将选择好的图片缩放                Bitmap bitSource = new Bitmap(sourceBitmap, sourceBitmap.Width, sourceBitmap.Height);                Rectangle cropRect = new Rectangle(x, y, cropWidth, cropHeight);                using (Bitmap newBitMap = new Bitmap(cropWidth, cropHeight))                {                    newBitMap.SetResolution(sourceBitmap.HorizontalResolution, sourceBitmap.VerticalResolution);                    using (Graphics g = Graphics.FromImage(newBitMap))                    {                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;                        g.SmoothingMode = SmoothingMode.HighQuality;                        g.PixelOffsetMode = PixelOffsetMode.HighQuality;                        g.CompositingQuality = CompositingQuality.HighQuality;                        g.DrawImage(bitSource, new Rectangle(0, 0, newBitMap.Width, newBitMap.Height), cropRect, GraphicsUnit.Pixel);                        return GetBitmapBytes(newBitMap);                    }                }            }        }        public static string GetBitmapBytes(Bitmap source)        {            ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[4];            EncoderParameters parameters = new EncoderParameters(1);            parameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);            using (MemoryStream tmpStream = new MemoryStream())            {                source.Save(tmpStream, codec, parameters);                byte[] data = new byte[tmpStream.Length];                tmpStream.Seek(0, SeekOrigin.Begin);                tmpStream.Read(data, 0, (int)tmpStream.Length);                string result = Convert.ToBase64String(data);                return result;            }        }        ///         /// 图片转换Base64        ///         /// 图片网络地址或本地路径        /// 
public static string ImageToBase64(string urlOrPath) { try { if (urlOrPath.Contains("http")) { Uri url = new Uri(urlOrPath); using (var webClient = new WebClient()) { var imgData = webClient.DownloadData(url); using (var ms = new MemoryStream(imgData)) { byte[] data = new byte[ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Read(data, 0, Convert.ToInt32(ms.Length)); string netImage = Convert.ToBase64String(data); return netImage; } } } else { FileStream fileStream = new FileStream(urlOrPath, FileMode.Open); Stream stream = fileStream as Stream; byte[] data = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(data, 0, Convert.ToInt32(stream.Length)); string netImage = Convert.ToBase64String(data); return netImage; } } catch (Exception) { return null; } } /// /// 按比例缩放图片 /// /// /// ///
public static string ResizeImage(Stream content, int resizeWidth, int resizeHeight) { using (Bitmap sourceBitmap = new Bitmap(content)) { int width = sourceBitmap.Width, height = sourceBitmap.Height; if (height > resizeHeight || width > resizeWidth) { if ((width * resizeHeight) > (height * resizeWidth)) { resizeHeight = (resizeWidth * height) / width; } else { resizeWidth = (width * resizeHeight) / height; } } else { resizeWidth = width; resizeHeight = height; } // 将选择好的图片缩放 Bitmap bitSource = new Bitmap(sourceBitmap, resizeWidth, resizeHeight); bitSource.SetResolution(sourceBitmap.HorizontalResolution, sourceBitmap.VerticalResolution); using (MemoryStream stream = new MemoryStream()) { bitSource.Save(stream, ImageFormat.Jpeg); byte[] data = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(data, 0, Convert.ToInt32(stream.Length)); string newImage = Convert.ToBase64String(data); return newImage; } } } }

效果图

 转载请标注原文地址:

转载于:https://www.cnblogs.com/JasonLong/p/4527030.html

你可能感兴趣的文章
Python-求素数程序
查看>>
如何去掉ECSHOP meta标签中的版本号
查看>>
【重构与模式】6.3 用Factory封装类
查看>>
Go语言interface详解
查看>>
ASP实现自动解析网页中的图片地址
查看>>
一个基于CSS3的网站
查看>>
策划了个.NET控件的案例大赛
查看>>
jdk安装配置环境变量
查看>>
Spring Batch JobExecutionDecider
查看>>
java守护线程的理解
查看>>
关于模版模式
查看>>
偶尔看到的c11新特性2
查看>>
控制并发访问资源 -- Semaphore
查看>>
for循环的简单例子:求100以内的偶数和
查看>>
真正聪明的人都是下笨功夫(深度好文)
查看>>
facebook160亿美元收购WhatsApp
查看>>
Python 05 自定义函数的创建、调用和函数
查看>>
千方百计获取百度网盘下载链接
查看>>
淘宝网页变为繁体,教你如何改回简体
查看>>
网页选项卡
查看>>