头像裁切一直是一个棘手的问题,网上一些裁切程序很多都是兼容*不太好,或者使用起来不方便。
今天,完善了一个头像裁切程序,来和大家分享。借助了jquery插件Jcrop,上传使用的是uploadify,经试验火狐、IE 6 7 8均通过,使用起来也极为方便
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="cut.aspx.cs" Inherits="cut" %>
<!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 runat="server">
<title>头像裁切</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<link href="ImgCut/css/jquery.Jcrop.css" rel="stylesheet" type="text/css" />[!--empirenews.page--]
<link href="uploadify/uploadify.css" rel="stylesheet" type="text/css" />
<script src="JS/jquery-1.4.3.min.js" type="text/javascript"></script>
<script src="uploadify/swfobject.js" type="text/javascript"></script>
<script src="uploadify/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>
<script src="ImgCut/js/jquery.Jcrop.min.js" type="text/javascript"></script>
<script type="text/javascript">
function CutLoad()
{
// Create variables (in this scope) to hold the API and image size
var jcrop_api, boundx, boundy;
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: 1,
minSize:[100,100]
},function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
[!--empirenews.page--]
// Store the API in the jcrop_api variable
jcrop_api = this;
jcrop_api.animateTo([boundx/2-50,boundy/2+50,boundx/2+50,boundy/2-50]);
});
function updatePreview(c)
{
if (parseInt(c.w) > 0)
{
var rx = 100 / c.w;
var ry = 100 / c.h;
$('#x1').val(c.x);
$('#y1').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
$('#preview').css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
};
}
function show()[!--empirenews.page--]
{
var src=GetImgSrcValue();
var SX= $('#x1').val();
var SY= $('#y1').val();
var W= $('#w').val();
var H= $('#h').val();
var width=$('#target').width();
$.ajax({
url:"ImgCut/ImgCut.ashx",
type:"post",
dataType:"xml",
data:{"pPath":src,"SX":SX,"SY":SY,"W":W,"H":H,"width":width},
beforeSend:function(XMLHttpRequest){
},
success:function(data,status){
if($(data).find("content").text()!="Error")
{
$("#Img1").attr("src",$(data).find("content").text()+"?img="+Math.random());
}
},
complete:function(data,status){
},
error:function(){
}
});
}
$(function(){
// CutLoad();
$("#uploadImg").uploadify({
'uploader': '/uploadify/uploadify.swf',[!--empirenews.page--]
'cancelImg': '/uploadify/images/cancel.png',
'buttonText': 'selectfile',
'buttonImg': '/uploadify/images/selectfiles.png',
'hideButton':false,
'width': 177,
'height': 30,
'script': '/ImgCut/UploadImg.ashx',
'fileDesc': '*.jpg;*.jpeg;*.bmp;*.png;',
'fileExt': '*.jpg;*.jpeg;*.bmp;*.png;',
'sizeLimit':1024*1024*2,
'simUploadLimit':1,
'multi':false,
'auto':true,
'onInit':function(){
},
'onSelect':function(event,queueID,fileObj){ [!--empirenews.page--]
},
'onSelectOnce':function(event,data){
},
'onComplete':function(event,queueID,fileObj,response,data){
var src=GetImgSrcValue();
if(src!="")
{
DeleteFile(src);
}
$("#SaveImgSrcValue").val("");
var responseArr=response.split("|");
var img_src=responseArr[0];
var img_width=parseInt(responseArr[1]);
var img_height=parseInt(responseArr[2]);
var margin_height;
var show_width;
if(img_width>=img_height)//如果是宽大于高比例[!--empirenews.page--]
{
if(img_width>=400)
{
margin_height=(400-(img_height*400/img_width))/2;
show_width=400;
}
else
{
margin_height=(400-img_height)/2;
show_width=img_width;
}
$("#tb").children().remove();
$("#tb").append("<div style="width:400px; height:400px; border:solid 2px #ddd; text-align:center;"><img src=""+img_src+"" id="target" width=""+show_width+"px" /></div><div style="width:100px;height:100px;overflow:hidden;"><img src=""+img_src+"" id="preview" width="100px" alt="Preview" />")[!--empirenews.page--]
}
else
{
if(img_height>=400)
{
show_width=img_width*400/img_height;
margin_height=0;
}
else
{
show_width=img_width;
margin_height=(400-img_height)/2;
}
$("#tb").children().remove();
$("#tb").append("<div style="width:400px; height:400px; border:solid 2px #ddd; text-align:center;"><img src=""+img_src+"" id="target" width=""+show_width+"px" /></div><div style="width:100px;height:100px;overflow:hidden;"><img src=""+img_src+"" id="preview" width="100px" alt="Preview" />")[!--empirenews.page--]
}
SaveImgSrcValue(queueID,fileObj,img_src);
//$("#tb").children().remove();
//$("#tb").append(" <div style="width:400px; height:400px; border:solid 3px #ddd; text-align:center"><img src=""+img_src+"" id="target" alt="Flowers" width=""+show_width+"px" /></div><div style="width:100px;height:100px;overflow:hidden;"><img src=""+img_src+"" id="preview" width="100px" alt="Preview" />")
if((img_width>100&&img_height>100))
{
CutLoad();
$(".jcrop-holder").css("margin","0 auto");
}
//$("#tb img").attr("src",response);
//SetImgQueue(queueID,fileObj,response);[!--empirenews.page--]
},
'onAllComplete':function(event,data){
},
'onCancel': function(event,queueID,fileObj,data){
},
'onError': function(event,queueID,fileObj,errorObj){
if(fileObj.size>1024*1024*2)
{
ale人体("单个文件大小不能大于2M!");
$("#uploadImg").uploadifyCancel(queueID);
}
}
});
});
//根据队列值获取src属*
function GetImgSrcByQueue(queueID)
{
var value=$("#SaveImgSrcValue").val();
var src="-1";
if(value!="")
{
var Arr=value.split("#");[!--empirenews.page--]
for(var i=0;i<Arr.length;i++)
{
var ChildArr=Arr[i].split("|");
if(ChildArr[0]==queueID)
{
src=ChildArr[3];
break;
}
}
}
return src;
}
//将路径信息保存在隐藏值中
function SaveImgSrcValue(queueID,fileObj,src)
{
if(src.indexOf("Error")==-1)
{
var value=$("#SaveImgSrcValue").val();
if(value=="")
{
$("#SaveImgSrcValue").val(queueID+"|"+fileObj.name+"|"+GetFileSize(fileObj.size)+"|"+src);
}
else
{
$("#SaveImgSrcValue").val(value+"#"+queueID+"|"+fileObj.name+"|"+GetFileSize(fileObj.size)+"|"+src);[!--empirenews.page--]
}
}
}
//删除上次图片
//删除图片
function DeleteFile(src)
{
$.ajax({
url:"/Shop/admin/DeleteLastImg.ashx",
type:"post",
dataType:"xml",
data:{"path":src},
beforeSend:function(XMLHttpRequest){
},
success:function(data,status){
if($(data).find("content").text()=="DeleteSuccess")
{
// $("#SaveImgSrcValue").val("");
}
},
complete:function(data,status){
},
error:function(){
}
});
}
//获取隐藏的属* 赋予图片 解决刷新问题
function GetImgSrcValue()
{
var value=$("#SaveImgSrcValue").val();
var src="";
if(value!="")
{
var Arr=value.split("#");
var ArrLast=Arr[Arr.length-1].split("|");
src=ArrLast[ArrLast.length-1];
}[!--empirenews.page--]
return src;
}
function SizeFormat(s)
{
s = s.replace(/^(d*)$/, "$1.");
s = (s + "00").replace(/(d*.dd)d*/, "$1");
s = s.replace(".", ",");
var re = /(d)(d{3},)/;
while (re.test(s))
s = s.replace(re, "$1,$2");
s = s.replace(/,(dd)$/, ".$1");
return s.replace(/^./, "0.")
}
function GetFileSize(iBytes)
{
var iFileKB = iBytes / 1024;
iFileKB = SizeFormat(iFileKB.toString());
return iFileKB + " KB";
}
</script>
</head>
<body>
<form id="form1" >
<div id="tb">
</div>
<input id="uploadImg" type="file" name="uploadImg" />
<input type="hidden" id="x1" /> [!--empirenews.page--]
<input type="hidden" id="y1" />
<input type="hidden" id="w" />
<input type="hidden" id="h" />
<input id="SaveImgSrcValue" type="hidden" name="SaveImgSrcValue" />
<img id="Img1" /><input id="Button1" type="button" value="生成头像" onclick="show();" />
</form>
</body>
</html>
ashx代码
<%@ WebHandler Language="C#" Class="UpLoadImg" %>
using System;
using System.Web;
using System.IO;
using System.Drawing;
public class UpLoadImg : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Expires = -1;
try
{
HttpPostedFile postedFile = context.Request.Files["Filedata"];
string savepath = "";[!--empirenews.page--]
string tempPath = "";
tempPath = "~/ImgCut/TempImages/";
savepath = context.Server.MapPath(tempPath);//实际保存文件夹路径
string filename = postedFile.FileName;
string sExtension = filename.Substring(filename.LastIndexOf('.'));
if (sExtension == ".jpg" || sExtension == ".jpeg" || sExtension == ".png" || sExtension == ".bmp")
{
if (!Directory.Exists(savepath))
{
Directory.CreateDirectory(savepath);
}
string sNewFileName = DateTime.Now.ToString("yyyyMMddhhmmssfff");
savepath = savepath + "/" + sNewFileName + sExtension;
postedFile.SaveAs(savepath);
System.Drawing.Image img = new System.Drawing.Bitmap(savepath);[!--empirenews.page--]
string width = img.Width.ToString();
string height = img.Height.ToString();
img.Dispose();
// string width = "400";
// string height = "400";
context.Response.Write("/ImgCut/TempImages/" + sNewFileName + sExtension+"|"+width+"|"+height);
context.Response.StatusCode = 200;
}
else
{
context.Response.Write("TypeError");
}
}
catch (Exception ex)
{
context.Response.Write("ServerError: " + ex.Message);
}
}
public bool IsReusable {
get {
return false;
}[!--empirenews.page--]
}
}
<%@ WebHandler Language="C#" Class="ImgCut" %>
using System;
using System.Web;
public class ImgCut : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/xml";
context.Response.Expires = -1;
try
{
if (context.Request.Form["pPath"] != null)
{
string pPath = context.Request.Form["pPath"].ToString();
string spPath=context.Server.MapPath("~"+pPath);
string pSavedPath = pPath.Replace("TempImages", "FaceImages");
string spSavedPath=context.Server.MapPath("~"+pSavedPath);
string pOrigSta人体PointX = context.Request.Form["SX"].ToString();
string pOrigSta人体PointY = context.Request.Form["SY"].ToString();[!--empirenews.page--]
string oPa人体Width = context.Request.Form["W"].ToString();
string oPa人体Height = context.Request.Form["H"].ToString();
int width = Conve人体.ToInt32(context.Request.Form["width"].ToString());
ImgHelper imghelper = new ImgHelper();
imghelper.GetPa人体(spPath, spSavedPath, 0, 0, 100, 100,Conve人体.ToInt32(pOrigSta人体PointX),Conve人体.ToInt32(pOrigSta人体PointY), Conve人体.ToInt32(oPa人体Width), Conve人体.ToInt32(oPa人体Height),width);
context.Response.Write("<content>" + pSavedPath + "</content>");
}
}
catch (Exception ex)
{
context.Response.Write("<content>Error</content>");
}
}
public bool IsReusable
{
get
{
return false;[!--empirenews.page--]
}
}
}
图片截取函数
/// <summary>
/// 获取图片指定部分
/// </summary>
/// <param name="pPath">图片路径</param>
/// <param name="pSavePath">保存路径</param>
/// <param name="pPa人体Sta人体PointX">目标图片开始绘制处的坐标X值(通常为)</param>
/// <param name="pPa人体Sta人体PointY">目标图片开始绘制处的坐标Y值(通常为)</param>
/// <param name="pPa人体Width">目标图片的宽度</param>
/// <param name="pPa人体Height">目标图片的高度</param>
/// <param name="pOrigSta人体PointX">原始图片开始截取处的坐标X值</param>
/// <param name="pOrigSta人体PointY">原始图片开始截取处的坐标Y值</param>
/// <param name="oPa人体Width">原图截取框图片的宽度</param>
/// <param name="oPa人体Height">原图截取框图片的高度</param>
/// <param name="pFormat">保存格式,通常可以是jpeg</param>
public void GetPa人体(string pPath, string pSavedPath, int pPa人体Sta人体PointX, int pPa人体Sta人体PointY, int pPa人体Width, int pPa人体Height, int pOrigSta人体PointX, int pOrigSta人体PointY, int oPa人体Width, int oPa人体Height, int showWidth)[!--empirenews.page--]
{
using (Image originalImg = Image.FromFile(pPath))
{
int width = originalImg.Width;
int height = originalImg.Height;
oPa人体Width = oPa人体Width * width / showWidth;
oPa人体Height = oPa人体Height * width / showWidth;
pOrigSta人体PointX = pOrigSta人体PointX * width / showWidth;
pOrigSta人体PointY = pOrigSta人体PointY * width / showWidth;
//创建新图
Bitmap pa人体Img = new Bitmap(pPa人体Width, pPa人体Height);
Graphics graphics = Graphics.FromImage(pa人体Img);
//绘制的大小 默认pPa人体Sta人体PointX=0,pPa人体Sta人体PointY=0 即为左上原点处绘制 pPa人体Width=100,pPa人体Height=100
Rectangle destRect = new Rectangle(new Point(pPa人体Sta人体PointX, pPa人体Sta人体PointY), new Size(pPa人体Width, pPa人体Height));//目标位置
//绘制的原图部分
Rectangle origRect = new Rectangle(new Point(pOrigSta人体PointX, pOrigSta人体PointY), new Size(oPa人体Width, oPa人体Height));//原图位置 [!--empirenews.page--]
//System.Drawing.Font f = new Font("Lucida Grande", 6);
//System.Drawing.Brush b = new SolidBrush(Color.Gray);
//设置高质量插值法
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.Clear(Color.White);
graphics.DrawImage(originalImg, destRect, origRect, GraphicsUnit.Pixel);
//G.DrawString("Ftodo.com", f, b,0,0);
graphics.Dispose();
originalImg.Dispose();
if (File.Exists(pSavedPath))
{
File.SetAttributes(pSavedPath, FileAttributes.Normal);
File.Delete(pSavedPath);
}
pa人体Img.Save(pSavedPath, ImageFormat.Jpeg);
pa人体Img.Dispose();[!--empirenews.page--]
}
}