最近有个微信项目的用户个人中心模块中,客户要求用户头像不仅仅只是上传图片,还需要能对图片进行裁剪。考虑到flash在IOS和Android上的兼容性问题,于是想着能从js这块入手,在网上发现了devotion博主写的《适应各浏览器图片裁剪无刷新上传js插件》文章,从中受到些许启发,以此为参考,进行了简单的修改。

新建一个页面,代码如下:

 <html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>图片裁剪</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
<link href="../css/jquery.Jcrop.min.css" rel="stylesheet" />
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../js/jquery.Jcrop.min.js"></script>
<script type="text/javascript" src="../js/imageCropperUpload.js"></script>
<style type="text/css">
#test
{
width: %;
height: %;
background-color: #;
position: absolute;
top: ;
left: ;
z-index: ;
opacity: 0.8;
/*兼容IE8及以下版本浏览器*/
filter: alpha(opacity=);
display: none;
} #fileList
{
width: %;
height: 500px;
/*background-color: #FF0;*/
margin: auto;
position: absolute;
z-index: ;
top: ;
bottom: ;
left: ;
right: ;
display: none;
text-align: center;
}
#divtest {
position: absolute;
z-index: ;
display: none;
bottom: 10px;
left: ;
width: %;
}
#divCancel
{
float: left;
width: 48px;
height: 32px;
line-height: 32px;
margin: 10px 20px;
background-color: #fff;
text-align: center;
cursor: pointer;
display: block;
}
#divConfirm
{
float: right;
width: 48px;
height: 32px;
line-height: 32px;
margin: 10px 20px;
background-color: #fff;
text-align: center;
cursor: pointer;
display: block;
}
</style>
<script type="text/javascript">
$(function () {
var btn = $("#selectFile");
btn.click(function () {
$("#test").show();
$("#fileList").show();
$("#divtest").show();
$("#divCancel").show();
$("#divConfirm").show();
}); $("#divCancel").click(function () {
$("#test").hide();
$("#fileList").hide();
$("#divtest").hide();
});
$("#divConfirm").click(function () {
$("#files").click();
}); btn.cropperUpload({
url: "../ajax/UploadPersonImage.ashx",//服务端处理图片
fileSuffixs: ["jpg", "png", "bmp"],
errorText: "{0}",
onComplete: function (msg) {
$("#divCancel").hide();
$("#divConfirm").hide();
if (msg == "false") {
alert("上传失败!");
return;
}
$("#testimg").attr("src", msg);
},
cropperParam: {//Jcrop参数设置,除onChange和onSelect不要使用,其他属性都可用
maxSize: [, ], //不要小于50,如maxSize:[40,24]
minSize: [, ], //不要小于50,如minSize:[40,24]
bgColor: "black",
bgOpacity: .,
allowResize: true,
allowSelect: true,
animationDelay:
},
perviewImageElementId: "fileList", //设置预览图片的元素id
perviewImgStyle: { width: '100%', height: '500px', border: '1px solid #ebebeb'}//设置预览图片的样式
}); var upload = btn.data("uploadFileData"); $("#files").click(function () {
upload.submitUpload();
$("#test").hide();
$("#fileList").hide();
$("#divtest").hide();
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<!-- 文件上传 start -->
<div style="width: 100%; float: left">
<input id="selectFile" type="button" value="选择文件" />
<input id="files" type="button" value="上传截图" style="display: none;" />
</div>
<!-- 文件上传 end --> <!-- 图片上传后展示的地方 start -->
<div id="testdiv" style="margin-top: 10px; width: 100%;">
<img alt="" src="" id="testimg" />
</div>
<!-- 图片上传后展示的地方 end --> <!-- 遮罩层 start -->
<div id="test"></div>
<div id="fileList">
</div>
<div id="divtest">
<div id="divCancel">取消</div>
<div id="divConfirm">确定</div>
</div>
<!-- 遮罩层 end -->
</form>
</body>
</html>

页面中jQuery.Jcrop.min.css和jquery.Jcrop.min.js是Jcrop插件必须的一个样式表文件和js文件,jquery可以自行下载,然后后面的imageCropperUpload.js文件是devotion博主写的插件,我自己简单的修改了一下,注意引用顺序不要弄错了,否则不起作用。

 (function ($) {
var defaultSettings = {
url: "uploadImg/", //上传地址
fileSuffixs: ["jpg", "png"], //允许上传的文件后缀名列表
errorText: "不能上传后缀为 {0} 的文件!", //错误提示文本,其中{0}将会被上传文件的后缀名替换
onCheckUpload: function (text) { //上传时检查文件后缀名不包含在fileSuffixs属性中时触发的回调函数,(text为错误提示文本)
},
onComplete: function (msg) { //上传完成后的回调函数[不管成功或失败,它都将被触发](msg为服务端的返回字符串)
alert(msg);
}, onChosen: function (file, obj, fileSize, errorTxt) { /*选择文件后的回调函数,(file为选中文件的本地路径;obj为当前的上传控件实例,
fileSize为上传文件大小,单位KB[只有在isFileSize为true时,此参数才有值],
errorTxt为获取文件大小时的错误文本提示) */
//alert(file);
},
cropperParam: {}, //图片截取参数设置,此参数即为Jcrop插件参数
isFileSize: false,//是否获取文件大小
perviewImageElementId: "",//用于预览上传图片的元素id(请传入一个div元素的id) perviewImgStyle: null//用于设置图片预览时的样式(可不设置,在不设置的情况下多文件上传时只能显示一张图片),如{ width: '100px', height: '100px', border: '1px solid #ebebeb' }
}; $.fn.cropperUpload = function (settings) { settings = $.extend({}, defaultSettings, settings || {}); return this.each(function () {
var self = $(this); var upload = new UploadAssist(settings); upload.createIframe(this); //绑定当前按钮点击事件
self.bind("click", function (e) {
upload.chooseFile();
}); //将上传辅助类的实例,存放到当前对象中,方便外部获取
self.data("uploadFileData", upload); //创建的iframe中的那个iframe,它的事件需要延迟绑定
window.setTimeout(function () {
$(upload.getIframeContentDocument().body).find("input[type='file']").change(function () {
if (!this.value) return;
var fileSuf = this.value.substring(this.value.lastIndexOf(".") + 1); //检查是否为允许上传的文件
if (!upload.checkFileIsUpload(fileSuf, upload.settings.fileSuffixs)) {
upload.settings.onCheckUpload(upload.settings.errorText.replace("{0}", fileSuf));
return;
} if (upload.settings.isFileSize) {
var size = perviewImage.getFileSize(this, upload.getIframeContentDocument());
var fileSize, errorTxt;
if (size == "error") {
errorTxt = upload.errorText;
} else {
fileSize = size;
}
//选中后的回调
upload.settings.onChosen(this.value, this, fileSize, errorTxt);
} else {
//选中后的回调
upload.settings.onChosen(this.value, this);
} //是否开启了图片预览
if (upload.settings.perviewImageElementId) {
var main = perviewImage.createPreviewElement("closeImg", this.value, upload.settings.perviewImgStyle);
$("#" + upload.settings.perviewImageElementId).append(main);
var div = $(main).children("div").get(0); perviewImage.beginPerview(this, div, upload.getIframeContentDocument(), upload);
$("#fileList").children().children("div").css("height", "100%").css("border", "none");
}
}); //为创建的iframe内部的iframe绑定load事件
$(upload.getIframeContentDocument().body.lastChild).on("load", function () {
var dcmt = upload.getInsideIframeContentDocument();
upload.submitStatus = true;
if (dcmt.body.innerHTML) { if (settings.onComplete) {
settings.onComplete(dcmt.body.innerHTML);
} dcmt.body.innerHTML = "";
}
});
}, 100);
});
};
})(jQuery); //上传辅助类
function UploadAssist(settings) {
//保存设置
this.settings = settings;
//创建的iframe唯一名称
this.iframeName = "upload" + this.getTimestamp();
//提交状态
this.submitStatus = true;
//针对IE上传获取文件大小时的错误提示文本
this.errorText = "请设置浏览器一些参数后再上传文件,方法如下(设置一次即可):\n请依次点击浏览器菜单中的\n'工具->Internet选项->安全->可信站点->自定义级别'\n在弹出的自定义级别窗口中找到 'ActiveX控件和插件' 项,将下面的子项全部选为 '启用' 后,点击确定。\n此时不要关闭当前窗口,再点击 '站点' 按钮,在弹出的窗口中将下面复选框的 '√' 去掉,然后点击 '添加' 按钮并关闭当前窗口。\n最后一路 '确定' 完成并刷新当前页面。"; this.jcropApi;
return this;
}
UploadAssist.prototype = {
//辅助类构造器
constructor: UploadAssist, //创建iframe
createIframe: function (/*插件中指定的dom对象*/elem) { var html = "<html>"
+ "<head>"
+ "<title>upload</title>"
+ "<script>"
+ "function getDCMT(){return window.frames['dynamic_creation_upload_iframe'].document;}"
+ "</" + "script>"
+ "</head>"
+ "<body>"
+ "<form method='post' target='dynamic_creation_upload_iframe' enctype='multipart/form-data' action='" + this.settings.url + "'>"
+ "<input type='text' id='x1' name='x1' />"
+ "<input type='text' id='y1' name='y1' />"
+ "<input type='text' id='x2' name='x2' />"
+ "<input type='text' id='y2' name='y2' />"
+ "<input type='text' id='w' name='w' />"
+ "<input type='text' id='h' name='h' />"
+ "<input type='text' id='maxW' name='maxW' />"
+ "<input type='text' id='maxH' name='maxH' />"
+ "<input type='file' name='fileUpload' />"
+ "</form>"
+ "<iframe name='dynamic_creation_upload_iframe'></iframe>"
+ "</body>"
+ "</html>"; this.iframe = $("<iframe name='" + this.iframeName + "'></iframe>")[0];
this.iframe.style.width = "0px";
this.iframe.style.height = "0px";
this.iframe.style.border = "0px solid #fff";
this.iframe.style.margin = "0px";
elem.parentNode.insertBefore(this.iframe, elem);
var iframeDocument = this.getIframeContentDocument();
iframeDocument.write(html);
}, //获取时间戳
getTimestamp: function () {
return (new Date()).valueOf();
},
//设置图片缩放的最大高宽
setMaxWidthAndHeight: function (/*最大宽*/maxW,/*最大高*/maxH) {
this.getElement("maxW").value = maxW;
this.getElement("maxH").value = maxH;
},
//设置图片截取参数
setImageCropperObj: function (/*图片截取对象*/obj) {
this.getElement("x1").value = obj.x;
this.getElement("y1").value = obj.y;
this.getElement("x2").value = obj.x2;
this.getElement("y2").value = obj.y2;
this.getElement("w").value = obj.w;
this.getElement("h").value = obj.h;
},
//获取创建的iframe中的元素
getElement: function (id) {
var dcmt = this.getIframeContentDocument();
return dcmt.getElementById(id);
},
//获取创建的iframe中的document对象
getIframeContentDocument: function () {
return this.iframe.contentDocument || this.iframe.contentWindow.document;
}, //获取创建的iframe所在的window对象
getIframeWindow: function () {
return this.iframe.contentWindow || this.iframe.contentDocument.parentWindow;
}, //获取创建的iframe内部iframe的document对象
getInsideIframeContentDocument: function () {
return this.getIframeWindow().getDCMT();
}, //获取上传input控件
getUploadInput: function () {
var inputs = this.getIframeContentDocument().getElementsByTagName("input");
var uploadControl;
this.forEach(inputs, function () {
if (this.type === "file") {
uploadControl = this;
return false;
}
});
return uploadControl;
}, //forEach迭代函数
forEach: function (/*数组*/arr, /*代理函数*/fn) {
var len = arr.length;
for (var i = 0; i < len; i++) {
var tmp = arr[i];
if (fn.call(tmp, i, tmp) == false) {
break;
}
}
}, //提交上传
submitUpload: function () {
if (!this.submitStatus) return; this.submitStatus = false; this.getIframeContentDocument().forms[0].submit();
}, //检查文件是否可以上传
checkFileIsUpload: function (fileSuf, suffixs) { var status = false;
this.forEach(suffixs, function (i, n) {
if (fileSuf.toLowerCase() === n.toLowerCase()) {
status = true;
return false;
}
});
return status;
}, //选择上传文件
chooseFile: function () {
if (this.settings.perviewImageElementId) {
$("#" + this.settings.perviewImageElementId).empty();
} var uploadfile = this.getUploadInput();
$(uploadfile).val("").click();
}
}; //图片预览操作
var perviewImage = {
timers: [],
//获取预览元素
getElementObject: function (elem) {
if (elem.nodeType && elem.nodeType === 1) {
return elem;
} else {
return document.getElementById(elem);
}
},
//开始图片预览
beginPerview: function (/*文件上传控件实例*/file, /*需要显示的元素id或元素实例*/perviewElemId, /*上传页面所在的document对象*/ dcmt, /*上传辅助类实例*/upload) {
this.imageOperation(file, perviewElemId, dcmt, upload);
},
//图片预览操作
imageOperation: function (/*文件上传控件实例*/file, /*需要显示的元素id或元素实例*/perviewElemId, /*上传页面所在的document对象*/ dcmt, /*上传辅助类实例*/upload) {
for (var t = 0; t < this.timers.length; t++) {
window.clearInterval(this.timers[t]);
}
this.timers.length = 0; var tmpParams = {
onChange: function (c) {
upload.setImageCropperObj(c);
},
onSelect: function (c) {
upload.setImageCropperObj(c);
}
};
var sWidth = 50, sHeight = 50;
if (upload.settings.cropperParam.minSize) {
var size = upload.settings.cropperParam.minSize;
sWidth = size[0] > sWidth ? size[0] : sWidth;
sHeight = size[1] > sHeight ? size[1] : sHeight;
}
var params = $.extend({}, tmpParams, upload.settings.cropperParam || {}); var preview_div = this.getElementObject(perviewElemId); var MAXWIDTH = preview_div.clientWidth;
var MAXHEIGHT = preview_div.clientHeight; upload.setMaxWidthAndHeight(MAXWIDTH, MAXHEIGHT); if (file.files && file.files[0]) { //此处为Firefox,Chrome以及IE10的操作
preview_div.innerHTML = "";
var img = document.createElement("img");
preview_div.appendChild(img);
img.style.visibility = "hidden";
img.onload = function () {
var rect = perviewImage.clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
img.style.width = rect.width + 'px';
img.style.height = rect.height + 'px';
img.style.visibility = "visible";
var offsetWidth = (rect.width / 2) - (sWidth / 2);
var offsetHeight = (rect.height / 2) - (sHeight / 2);
var obj = {
x: offsetWidth,
y: offsetHeight,
x2: offsetWidth + sWidth,
y2: offsetHeight + sHeight,
w: sWidth,
h: sHeight
}; $(img).Jcrop(params, function () {
upload.jcropApi = this; this.animateTo([obj.x, obj.y, obj.x2, obj.y2]);
upload.setImageCropperObj(obj);
});
}; var reader = new FileReader();
reader.onload = function (evt) {
img.src = evt.target.result;
};
reader.readAsDataURL(file.files[0]);
} else { //此处为IE6,7,8,9的操作
file.select();
var src = dcmt.selection.createRange().text; var div_sFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + src + "')";
var img_sFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src='" + src + "')"; preview_div.innerHTML = "";
var img = document.createElement("div");
preview_div.appendChild(img);
img.style.filter = img_sFilter;
img.style.visibility = "hidden";
img.style.width = "100%";
img.style.height = "100%"; function setImageDisplay() {
var rect = perviewImage.clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
preview_div.innerHTML = "";
var div = document.createElement("div");
div.style.width = rect.width + 'px';
div.style.height = rect.height + 'px';
div.style.filter = div_sFilter;
var offsetWidth = (rect.width / 2) - (sWidth / 2);
var offsetHeight = (rect.height / 2) - (sHeight / 2);
var obj = {
x: offsetWidth,
y: offsetHeight,
x2: offsetWidth + sWidth,
y2: offsetHeight + sHeight,
w: sWidth,
h: sHeight
};
preview_div.appendChild(div);
$(div).Jcrop(params, function () {
upload.jcropApi = this;
this.animateTo([obj.x, obj.y, obj.x2, obj.y2]);
upload.setImageCropperObj(obj);
});
} //图片加载计数
var tally = 0; var timer = window.setInterval(function () {
if (img.offsetHeight != MAXHEIGHT) {
window.clearInterval(timer);
setImageDisplay();
} else {
tally++;
}
//如果超过两秒钟图片还不能加载,就停止当前的轮询
if (tally > 20) {
window.clearInterval(timer);
setImageDisplay();
}
}, 100); this.timers.push(timer);
}
},
//按比例缩放图片
clacImgZoomParam: function (maxWidth, maxHeight, width, height) {
var param = { width: width, height: height };
if (width > maxWidth || height > maxHeight) {
var rateWidth = width / maxWidth;
var rateHeight = height / maxHeight; if (rateWidth > rateHeight) {
param.width = maxWidth;
param.height = Math.round(height / rateWidth);
} else {
param.width = Math.round(width / rateHeight);
param.height = maxHeight;
}
} param.left = Math.round((maxWidth - param.width) / 2);
param.top = Math.round((maxHeight - param.height) / 2);
return param;
},
//创建图片预览元素
createPreviewElement: function (/*关闭图片名称*/name, /*上传时的文件名*/file, /*预览时的样式*/style) {
var img = document.createElement("div");
img.title = file;
img.style.overflow = "hidden";
for (var s in style) {
img.style[s] = style[s];
} //var text = document.createElement("div");
//text.style.width = style.width;
//text.style.overflow = "hidden";
//text.style.textOverflow = "ellipsis";
//text.style.whiteSpace = "nowrap";
//text.innerHTML = file; var main = document.createElement("div");
main.appendChild(img);
//main.appendChild(text);
return main;
}, //获取上传文件大小
getFileSize: function (/*上传控件dom对象*/file, /*上传控件所在的document对象*/dcmt) {
var fileSize;
if (file.files && file.files[0]) {
fileSize = file.files[0].size;
} else {
file.select();
var src = dcmt.selection.createRange().text;
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileObj = fso.getFile(src);
fileSize = fileObj.size;
} catch (e) {
return "error";
}
}
fileSize = ((fileSize / 1024) + "").split(".")[0];
return fileSize;
}
};

然后新建一个一般预处理文件或者页面,都可以。以上面的“UploadPersonImage.ashx”为例,代码如下:

     /// <summary>
/// UploadPersonImage 的摘要说明
/// </summary>
public class UploadPersonImage : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
var x = context.Request.Params["x1"]; //水平偏移量
var y = context.Request.Params["y1"]; //垂直偏移量
var x2 = context.Request.Params["x2"]; //水平偏移量 + 截取宽度
var y2 = context.Request.Params["y2"]; //垂直偏移量 + 截取高度
var w = context.Request.Params["w"]; //截取宽度
var h = context.Request.Params["h"]; //截取高度
var maxW = context.Request.Params["maxW"];//客户端截取时,图片的最大宽度
var maxH = context.Request.Params["maxH"];//客户端截取时,图片的最大高度 if (string.IsNullOrEmpty(x) || string.IsNullOrEmpty(y) || string.IsNullOrEmpty(w) || string.IsNullOrEmpty(h) || string.IsNullOrEmpty(maxW) || string.IsNullOrEmpty(maxH))
{
context.Response.Write("false");
return;
} HttpFileCollection files = context.Request.Files;
if (files == null || files.Count <= )
{
context.Response.Write("false");
return;
}
// 服务器端存储文件的文件夹(磁盘路径)
string path = context.Server.MapPath("/");
const string imgpath = "WeixinPage/uploadImg"; //保存地址
if (Directory.Exists(path + imgpath) == false)
{
//如果不存在就创建file文件夹
Directory.CreateDirectory(path + imgpath);
} var fileName = string.Empty;
for (var i = ; i < files.Count; i++)
{
//首先将图片缩放到与客户端截取时的大小一致
using (var bitmap = GenerateThumbnail(int.Parse(maxW), int.Parse(maxH), files[i].InputStream))
{
fileName = "/" + DateTime.Now.Ticks + ".jpg";
var newFileName = path + imgpath + fileName;
try
{
//开始截取
ImageCropper(bitmap, int.Parse(w), int.Parse(h), int.Parse(x), int.Parse(y), newFileName,
System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex)
{
context.Response.Write("false");
return;
}
}
} //上传成功,输出图片相对路径
context.Response.Write("../uploadImg" + fileName); //上传失败
context.Response.Flush();
} /// <summary>
/// 生成指定大小的图片
/// </summary>
/// <param name="maxWidth">生成图片的最大宽度</param>
/// <param name="maxHeight">生成图片的最大高度</param>
/// <param name="imgFileStream">图片文件流对象</param>
private System.Drawing.Bitmap GenerateThumbnail(int maxWidth, int maxHeight, System.IO.Stream imgFileStream)
{
using (var img = System.Drawing.Image.FromStream(imgFileStream))
{
var sourceWidth = img.Width;
var sourceHeight = img.Height; var thumbWidth = sourceWidth; //要生成的图片的宽度
var thumbHeight = sourceHeight; //要生成图片的的高度 //计算生成图片的高度和宽度
if (sourceWidth > maxWidth || sourceHeight > maxHeight)
{
var rateWidth = (double)sourceWidth / maxWidth;
var rateHeight = (double)sourceHeight / maxHeight; if (rateWidth > rateHeight)
{
thumbWidth = maxWidth;
thumbHeight = (int)Math.Round(sourceHeight / rateWidth);
}
else
{
thumbWidth = (int)Math.Round(sourceWidth / rateHeight);
thumbHeight = maxHeight;
}
} var bmp = new System.Drawing.Bitmap(thumbWidth, thumbHeight);
//从Bitmap创建一个System.Drawing.Graphics对象,用来绘制高质量的缩小图。
using (var gr = System.Drawing.Graphics.FromImage(bmp))
{
//设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//下面这个也设成高质量
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//下面这个设成High
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //把原始图像绘制成上面所设置宽高的缩小图
var rectDestination = new System.Drawing.Rectangle(, , thumbWidth, thumbHeight);
gr.DrawImage(img, rectDestination, , , sourceWidth, sourceHeight,
System.Drawing.GraphicsUnit.Pixel);
return bmp;
}
}
}
/// <summary>
/// 截取图片中的一部分
/// </summary>
/// <param name="img">待截取的图片</param>
/// <param name="cropperWidth">截取图片的宽</param>
/// <param name="cropperHeight">截取图片的高</param>
/// <param name="offsetX">水平偏移量</param>
/// <param name="offsetY">垂直偏移量</param>
/// <param name="savePath">截取后的图片保存位置</param>
/// <param name="imgFormat">截取后的图片保存格式</param>
private void ImageCropper(System.Drawing.Image img, int cropperWidth, int cropperHeight, int offsetX,
int offsetY, string savePath,
System.Drawing.Imaging.ImageFormat imgFormat)
{
using (var bmp = new System.Drawing.Bitmap(cropperWidth, cropperHeight))
{
//从Bitmap创建一个System.Drawing.Graphics对象,用来绘制高质量的缩小图。
using (var gr = System.Drawing.Graphics.FromImage(bmp))
{
//设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//下面这个也设成高质量
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//下面这个设成High
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //把原始图像绘制成上面所设置宽高的截取图
var rectDestination = new System.Drawing.Rectangle(offsetX, offsetY, cropperWidth, cropperHeight);
gr.DrawImage(img, , , rectDestination,
System.Drawing.GraphicsUnit.Pixel); //保存截取的图片
bmp.Save(savePath, imgFormat);
}
}
} public bool IsReusable
{
get
{
return false;
}
}
}

以上算是基本实现了,下面给出相应的效果图。

Jcrop插件的下载地址:http://code.ciaoca.com/jquery/jcrop/

参考博客文章链接地址:http://blog.csdn.net/sq111433/article/details/17562703

ASP.NET简单实现APP中用户个人头像上传和裁剪的更多相关文章

  1. 在MVC应用程序中,怎样删除上传的文件

    在ASP.NET MVC应用程序中,怎样删除上传的文件. 由于上传时,真正文件是存储在应用程序某一目录,在数据库表中,只是存储其基本信息.在删除时,需要注意一下,由于没有事务可操作.Insus.NET ...

  2. ASP.NET 中对大文件上传的简单处理

    在 ASP.NET 开发的过程中,文件上传往往使用自带的 FileUpload 控件,可是用过的人都知道,这个控件的局限性十分大,最大的问题就在于上传大文件时让开发者尤为的头疼,而且,上传时无法方便的 ...

  3. ASP.NET中扩展FileUpload的上传文件的容量

    ASP.NET中扩展FileUpload只能上传小的文件,大小在4MB以内的.如果是上传大一点的图片类的可以在web.config里面扩展一下大小,代码如下 <system.web> &l ...

  4. node.js+react全栈实践-Form中按照指定路径上传文件并

    书接上回,讲到“使用同一个新增弹框”中有未解决的问题,比如复杂的字段,文件,图片上传,这一篇就解决文件上传的问题.这里的场景是在新增弹出框中要上传一个图片,并且这个上传组件放在一个Form中,和其他文 ...

  5. Laravel中的日志与上传

    PHP中的框架众多,我自己就接触了好几个.大学那会啥也不懂啥也不会,拿了一个ThinkPHP学了.也许有好多人吐槽TP,但是个人感觉不能说哪个框架好,哪个框架不好,再不好的框架你能把源码读上一遍,框架 ...

  6. 从web编辑器 UEditor 中单独提取图片上传,包含多图片单图片上传以及在线涂鸦功能

    UEditor是由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码.(抄的...) UEditor是非常好用的富文 ...

  7. asp.net core 如何集成kindeditor并实现图片上传功能

     准备工作 1.visual studio 2015 update3开发环境 2.net core 1.0.1 及以上版本  目录 新建asp.net core web项目 下载kindeditor ...

  8. day105:Mofang:设置页面初始化&更新头像/上传头像&设置页面显示用户基本信息

    目录 1.设置页面初始化 2.更新头像 1.点击头像进入更新头像界面 2.更新头像页面初始化 3.更新头像页面CSS样式 4.头像上传来源选择:相册/相机 5.调用api提供的本地接口从相册/相机提取 ...

  9. asp.net web常用控件FileUpload(文件上传控件)

    FileUpload控件的主要中能:向指定目录上传文件,该控件包括一个文本框和一个浏览按钮. 常用的属性:FileBytes,FileContent.FileName.HasFile.PostedFi ...

随机推荐

  1. JAVA 1.9 面向对象之封装

    1. 面向对象程序设计的三大基本特征:继承(Inheritence).封装(Encapsulation).多态(Polymorphism)2. 封装:类包含了数据与方法,将数据与方法放在一个类中就构成 ...

  2. log4jWARN Please initialize the log4j system properly解决办法

    原因是没有对log4j这个jar进行文件配置. 要解决这个问题非常简单,建立LOG4J 的配置文件即可.在src 目录下创建配置文件,选择菜单File > New > File,文件名输入 ...

  3. Memcached的使用

    为什么要使用Memcached? 1)高并发访问数据库的痛:死锁 2)磁盘IO之痛 3)读写性能完美 4)超简单的集群搭建Cluster 5)开源 6)性能最佳 7)丰富的成功案例 Memcached ...

  4. C#操作SQL Server数据库

    http://www.cnblogs.com/rainman/archive/2012/03/13/2393975.html

  5. 数据库DDL审计

    一.为什么需要数据库DDL审计? DDL在生产系统中扮演非常重要的作用. 1)首先从业务角度来说,DDL可能意味着表结构变更,意味着新的版本即将发布,是个重要的时刻. 2)其次从运维角度来说,DDL尤 ...

  6. Oracle笔记二

    一.数据库语言分类  二.DML之数据插入 把一个表中的数据查询出来插入另外一个表中. create table student(id number,name varchar2(20),age num ...

  7. Python网络连接

    import appuifw as ui import httplib from os import abort uia=ui.app uin=ui.note uiq=ui.query e32=ui. ...

  8. CentOS6.3修复模式/单用户模式修改fstab文件

    今天修改LVM逻辑卷的名称时候,忘记更改fstab配置文件了,导致机器重启后找不到盘,进不了系统!立即用光盘进入修复模式进行修复!  1.修复模式操作方法: 用光盘进入Linux修复模式,插入cent ...

  9. 搭建Kafka集群(3-broker)

    Apache Kafka是一个分布式消息发布订阅系统,而Kafka环境往往是在集群中配置的.本篇就对配置3个broker的Kafka集群进行介绍. Zookeeper集群 Kafka本身提供了启动了z ...

  10. ASP.NET MVC增删改查

    ASP.NET MVC中的增删改查 基本都要使用C控制器中的两个action来完成操作,一个用于从主界面跳转到新页面.同时将所需操作的数据传到新界面,另一个则对应新界面的按钮,用于完成操作.将数据传回 ...