須要用到的jquery插件Jcrop 、Jquery.formjavascript
百度webuploader插件( http://fex.baidu.com/webuploader/ )css
引用下載好的css和js文件html
<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文件java
<script src="@Url.Content("~/Scripts/jquery.form.js")" type="text/javascript"></script>
佈局jquery
<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代碼git
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控制器github
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); } }
圖片處理類web
/// <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; } } } }
效果圖ajax
轉載請標註原文地址:http://www.cnblogs.com/JasonLong/p/4527030.htmljson