利用swfupload上传头像,利用Jcrop来实现头像在线选择,然后提交个ashx对原头像进行剪切。代码如下:

default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Jcrop._default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Jcrop测试</title>
<script type="text/javascript" src="JS/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="JS/swfupload/swfupload.js"></script>
<script type="text/javascript" src="JS/swfupload/handlers.js"></script>
<script type="text/javascript" src="JS/Jcrop/js/jquery.Jcrop.min.js"></script>
<script type="text/javascript" src="JS/Jcrop/js/jquery.color.js"></script>
<script type="text/javascript" src="JS/mytest.js"></script>
<link href="JS/Jcrop/css/jquery.Jcrop.min.css" rel="Stylesheet" type="text/css" />
<link href="CSS/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
upload_url: "imgUpload.ashx",
post_params: {
"ASP.NET_SESSIONID": "<%=Session.SessionID %>",
"ASPSESSID": "<%=Session.SessionID %>"
}, file_size_limit: "1024",
file_types: "*.jpg",
file_types_description: "JPG Images",
file_upload_limit: "-1", file_queue_error_handler: fileQueueError,
file_dialog_complete_handler: fileDialogComplete,
upload_progress_handler: uploadProgress,
upload_error_handler: uploadError,
upload_success_handler: uploadSuccess,
upload_complete_handler: uploadComplete, button_image_url: "/Image/swfupload/XPButtonNoText_160x22.png",
button_width: "160",
button_height: "22",
button_placeholder_id: "spanButtonPlaceHolder1",
button_text: '<span class="theFont">选择文件</span>',
button_text_style: ".theFont { font-size: 13;}",
button_text_left_padding: 12,
button_text_top_padding: 3,
button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE, //SWFUplaod.BUTTON_ACTION.SELECT_FILES 可以多选文件
flash_url: "/JS/swfupload/swfupload.swf", custom_settings: {
upload_target: "divFileProgressContainer1"
},
debug: false
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td height="25" width="30%" align="right">
用户头像 :
</td>
<td height="25" width="*" align="left">
<div id="swfu_container1" style="margin: 0px 10px;">
<div>
<span id="spanButtonPlaceHolder1"></span>
</div>
<div id="divFileProgressContainer1" style="height: 75px;">
</div>
<div id="thumbnails1">
<div id="div_addPhoto">
<img alt="用户头像" id="img_UserPhoto1" name="img_UserPhoto1" />
</div>
<input type="hidden" runat="server" id="userphoto1" />
</div>
<div id="div_photoadd" style="width: 100px; height: 100px; overflow: hidden; display: none">
<img alt="用户头像" id="viewUserPhoto" />
</div>
<input type="button" id="btn_imgcut" style="display: none" onclick="checkCoords($('#x').val(), $('#y').val(), $('#w').val(), $('#h').val(), $('#userphoto1').val())"
value="剪切头像" />
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
</div>
</td>
</tr>
</table>
</form>
</body>
</html>

mytest.js

//*************头像剪切 Code By:5653325 http://blog.csdn.net/5653325*********************
var xy_x, xy_y; function JcropInit() {
$('#img_UserPhoto1').Jcrop({
bgOpacity: 0.5,
onChange: updateCoords,
onSelect: updateCoords,
keySupport: false,
aspectRatio: 1,
bgColor: 'white',
addClass: 'jcrop-normal'
}, function () {
var xy = this.getBounds();
xy_x = xy[0];
xy_y = xy[1];
api = this;
api.setSelect([1, 1, 100, 100]);
api.setOptions({ bgFade: true, bgColor: $.Jcrop.defaults.bgColor, bgOpacity: $.Jcrop.defaults.bgOpacity });
});
};
function updateCoords(c) {
if (parseInt(c.w) > 0) {
var rx = 100 / c.w;
var ry = 100 / c.h;
$('#viewUserPhoto').css({
width: Math.round(rx * xy_x) + 'px',
height: Math.round(ry * xy_y) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};
//头像剪切 function checkCoords(x, y, w, h, f) {
if (x < 0 || y < 0 || w < 10 || h < 10) {
alert('选择图片太小,无法剪切。');
return false;
}
else {
$.ajax({
type: "POST",
data: "cmd=cut&t=" + Math.random() + "&x=" + x + "&y=" + y + "&w=" + w + "&h=" + h + "&f=" + f,
url: "imgCut.ashx",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "text",
success: function (text) {
var dataobj = eval(text);
if (dataobj[0].count == 0) {
alert(dataobj[0].list[0].error);
}
else {
$('#div_addPhoto').empty();
$('#div_addPhoto').append("<img alt='用户头像' id='img_UserPhoto1' name='img_UserPhoto1' />");
$("#img_UserPhoto1").attr("src", dataobj[0].list[0].path + "?t=" + Math.random());
$("#viewUserPhoto").attr("src", dataobj[0].list[0].path + "?t=" + Math.random());
$("#div_photoadd").css("display", 'none');
$("#btn_imgcut").css("display", 'none');
}
},
error: function (request, message, ex) {
alert("错误:" + message);
}
});
}
};

swfupload下的handler.js的某个函数修改

function uploadSuccess(file, serverData) {
try
{
//*************头像剪切 Code By:5653325 http://blog.csdn.net/5653325*********************
$('#div_addPhoto').empty();
$('#div_addPhoto').append("<img alt='用户头像' id='img_UserPhoto1' name='img_UserPhoto1' />");
$("#img_UserPhoto1").attr("src", serverData + "?t=" + Math.random());
$("#userphoto1").val(serverData);
$("#viewUserPhoto").attr("src", serverData + "?t=" + Math.random());
$("#div_photoadd").css("display", '');
$("#btn_imgcut").css("display", '');
JcropInit();
} catch (ex) {
this.debug(ex);
}
}

图片上传ashx(imageupload.ashx)

<%@ WebHandler Language="C#" Class="imgUpload" %>

using System;
using System.Web;
using System.IO;
public class imgUpload : IHttpHandler
{ public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string updir = context.Server.MapPath(@"~\Upload\userphoto") + "\\";
if (context.Request.Files.Count > 0)
{
try
{
for (int j = 0; j < context.Request.Files.Count; j++)
{
HttpPostedFile uploadFile = context.Request.Files[j];
if (uploadFile.ContentLength > 0)
{
if (!Directory.Exists(updir))
{
Directory.CreateDirectory(updir);
}
string extname = Path.GetExtension(uploadFile.FileName);
string fullname =Guid.NewGuid().ToString();
string filename = uploadFile.FileName; uploadFile.SaveAs(string.Format("{0}{1}", updir, fullname + extname));
context.Response.Write(string.Format(@"/Upload/userphoto/{0}", fullname + extname));
}
}
}
catch (Exception ex)
{
context.Response.Write("Message" + ex.ToString());
}
}
} public bool IsReusable {
get {
return false;
}
} }

图片剪切的ashx(imgcut.ashx)

<%@ WebHandler Language="C#" Class="imgCut" %>

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
public class imgCut : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
int x = 1, y = 1, w = 1, h = 1;
string f = string.Empty;
if (context.Request["x"] == null || context.Request["y"] == null || context.Request["w"] == null || context.Request["h"] == null)
{
context.Response.Write("[{count:0,list:[{\"error\":\"参数不正确。\"}]}]");
context.Response.End();
}
if (context.Request["f"] == null)
{
context.Response.Write("[{count:0,list:[{\"error\":\"没有图片文件。\"}]}]");
context.Response.End();
}
else
{
f = context.Request["f"].ToString().Replace("/", "\\");
}
try
{
x = int.Parse(context.Request["x"].ToString());
y = int.Parse(context.Request["y"].ToString());
w = int.Parse(context.Request["w"].ToString());
h = int.Parse(context.Request["h"].ToString());
}
catch
{
context.Response.Write("[{count:0,list:[{\"error\":\"参数不能被识别。\"}]}]");
context.Response.End();
}
if (!File.Exists(context.Server.MapPath("~\\" + f)))
{
context.Response.Write("[{count:0,list:[{\"error\":\"图片文件不存在。\"}]}]");
context.Response.End();
} Bitmap b;
Graphics g;
using (Image img = System.Drawing.Image.FromFile(context.Server.MapPath("~\\" + f)))
{
b = new Bitmap(w, h, img.PixelFormat);
b.SetResolution(img.HorizontalResolution, img.VerticalResolution);
g = Graphics.FromImage(b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.Half;
g.DrawImage(img, new Rectangle(0, 0, w, h),new Rectangle(x, y, w, h), GraphicsUnit.Pixel);
img.Dispose();
}
string ff = context.Server.MapPath("~\\" + f);
b.Save(ff);
b.Dispose();
g.Dispose();
context.Response.Write("[{count:1,list:[{\"path\":\"" + f.Replace("\\", "/") + "\"}]}]");
context.Response.End();
} public bool IsReusable
{
get
{
return false;
}
} }

源码稍候放出(资源审核中……),请关注http://download.csdn.net/user/5653325第一时间获取源码。

ASP.NET实现头像剪切保存的更多相关文章

  1. WPF 自定义图片剪切器 - 头像剪切(扩展与完善、实时截图)

    原文:WPF 自定义图片剪切器 - 头像剪切(扩展与完善.实时截图) 一.说明:上一次写的"WPF 自定义图片剪切器 - 头像剪切.你懂得"存在明显的缺陷,由于篇幅较长.重新写了一 ...

  2. html5,js插件实现手机端实现头像剪切上传

    思路:先打开相册,选取图片,在剪切图片,转化为base64格式,然后上传到七牛存储,返回url,再传给后端,整个流程就是这样.用的是angular框架,图像插件用到imagecropper.js,废话 ...

  3. ASP.Net如何用Cookies保存对象

    在ASP.Net中,有时候考虑到较多的使用Session来保存对象,会增加服务器的负载,所以我们会选择用Cookies来保存对象的状态,而Cookies只能保存字符串,这时,我们可以考虑用序列化操作来 ...

  4. ASP.NET下载远程图片保存到本地的方法、保存抓取远程图片

    以下介绍两种方法:1.利用WebRequest,WebResponse 类 WebRequest wreq=WebRequest.Create("http://www.xueit.com/e ...

  5. asp.net 生成 excel导出保存时, 解决迅雷下载aspx页面问题

    网络上搜索,一大堆废话,以下为简单的导出生成Excel代码: string excelFile = Server.MapPath("~/SB/UpFile/20151104111008/Bo ...

  6. andrid 上传图片 asp.net 后台接收并保存

    android 端代码 package com.example.uploadfile; import java.io.DataOutputStream; import java.io.File; im ...

  7. ASP.NET MVC实现剪切图片

    开发需要,我们需要对某一张图片进行剪切.就是说,获取图片某一区域.下面Insus.NET教大家轻便容易实现它. 首先写好一个处理函数,它建在MVC应用程序结构Utilities目录下: 准备好一张图片 ...

  8. C# ASP.NET 手写板并生成图片保存

    前端: @{ Layout = null; } <!DOCTYPE html> <html lang="zh-CN"> <head> <t ...

  9. 使用jcrop进行头像剪切

    http://www.cnblogs.com/chenssy/archive/2013/05/18/3084985.html http://code.ciaoca.com/jquery/jcrop/ ...

随机推荐

  1. linux 使用笔记6

    ---恢复内容开始--- 1.内容追加 把一个文件的内容追加到另一个文件中: cat first.txt >> second.txt//追加到second.txt文件的末端    cat ...

  2. java itext 报错 com.itextpdf.text.DocumentException: Font 'STSong-Light' with 'UniGB-UCS2-H'

    com.itextpdf.text.DocumentException: Font 'STSong-Light' with 'UniGB-UCS2-H' 解决方案 <dependency> ...

  3. openssl AES加密

    此代码不涉及ECB和CBC等关联加密 #include <stdio.h> #include <string.h> #include <stdlib.h> #inc ...

  4. 华为QOS原理及配置

    http://www.tudou.com/programs/view/GWCiHfWC9FI/ FLASH : http://www.tudou.com/v/GWCiHfWC9FI/&reso ...

  5. ubuntu samba共享后windows读写文件都是以nogroup问题

    添加smb账号 sudo smbpasswd -a xxx 如果报错:Failed to add entry for user xxx 则是因为这个账号不存在 添加成功以后,过一会就可以重新登陆了(u ...

  6. 使用SpringMVC的@CrossOrigin注解解决跨域请求问题

    跨域问题,通俗说就是用ajax请求其他站点的接口,浏览器默认是不允许的.同源策略(Same-orgin policy)限制了一个源(orgin)中加载脚本或脚本与来自其他源(orgin)中资源的交互方 ...

  7. JavaScript的进阶篇

    一.Array对象.数组对象 1)创建数组对象 //Array 对象用于在单个的变量中存储多个值. //语法: //创建方式1: ,,]; //创建方式2: new Array(); // 创建数组时 ...

  8. pycharm显示Unresolved reference

    状态:已解决 原因:不知道怎么表达 解决方法:重装django,,,,,,,,,,,,,,,,,,,

  9. Eclipse中配置约束

    一.本地配置schema约束(xsd文件): 1.比如配置spring的applicationContext.xml中的约束条件: 复制applicationContext.xml中如图: 2.win ...

  10. 如何将frm文件导入MySql数据库

    只要在mysql的安装文件中找到data文件夹,然后在里面建立一个文件夹,比如test.这个test其实就对应着数据库的名称,所以,你想要起什么样的数据库名称就把文件夹起什么名字. 然后把.frm文件 ...