ASP.NET MVC4使用JCrop裁剪图片并上传

需要用到的jquery插件Jcrop 、Jquery.form

百度webuploader插件( http://fex.baidu.com/webuploader/ )

引用下载好的css和js文件

<link href="@Url.Content("~/Scripts/Jcrop/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>

布局

 <div role="tabpanel" class="tab-pane" id="div_headportrait">
     @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")

             <div class="form-horizontal">
                    <div class="form-group">
                       <div class="col-lg-3">当前头像</div>
                        <div class="col-lg-5">
                              <div>设置新头像</div>
                                  <div>支持jpg、jpeg、gif、png或者bmp格式,可以在大照片中裁剪满意的部分。</div>
                                     <div id="btnBrowserPic">选 择</div> <!--这里使用的是百度webuploader插件-->
                                  </div>
                                    <div class="col-lg-3">预览头像</div>
                                </div>

                                <div class="form-group">
                                    <div class="col-lg-3">
                                        <img alt="当前头像" id="imgCurrent" style="width: 100px; height: 100px;" @(string.IsNullOrEmpty(Model.HeadPortraitUrl) ? "" : "src=data:image/bmp;base64," + Model.HeadPortraitData + "") />
                                    </div>
                                    <div class="col-lg-5 div-origin" style="height:300px;height:300px;">
                                        <img id="imgOrigin" style="max-width:300px;max-height:300px;" />
                                    </div>
                                    <div class="col-lg-3">
                                        <div style="width:100px;height:100px;overflow:hidden;margin-left:5px;">
                                            <img id="imgCropped" style="max-width:300px;max-height:300px;" />
                                        </div>
                                    </div>
                                </div>

                     <div class="form-group text-center">
                          <input type="button" value="保 存" id="btn_save" class="btn btn-primary" />
                   </div>
          </div>
     }
</div>

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('<img id="imgOrigin" style="max-width:300px;max-height:300px;" />'); 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);
        }
    }


图片处理类

    /// <summary>
    /// 图片处理
    /// </summary>
    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;
            }
        }


        /// <summary>
        /// 图片转换Base64
        /// </summary>
        /// <param name="urlOrPath">图片网络地址或本地路径</param>
        /// <returns></returns>
        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;
            }
            
        }

        /// <summary>
        /// 按比例缩放图片
        /// </summary>
        /// <param name="content"></param>
        /// <param name="resizeWidth"></param>
        /// <returns></returns>
        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.cnblogs.com/JasonLong/p/4527030.html

你可能感兴趣的:(ASP.NET MVC4使用JCrop裁剪图片并上传)