[asp.net core]ASP.NET MVC4使用JCrop裁剪图片并上传的例子

更新时间:2020-03-27    来源:ASP.NET MVC    手机版     字体:

【www.bbyears.com--ASP.NET MVC】

引用下载好的css和js文件

 代码如下 jquery.Jcrop.min.css")" rel="stylesheet" />
<script src="@Url.Content("~/Scripts/Jcrop/jquery.Jcrop.min.js")" type="text/javascript"></script>

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

 代码如下 <script src="@Url.Content("~/Scripts/jquery.form.js")" type="text/javascript"></script>

布局

 代码如下
 
     @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;
                }
            }
        }
    }


效果图

本文来源:http://www.bbyears.com/asp/89967.html