ASP.NET使用Jcrop實現頭像線上編輯儲存
阿新 • • 發佈:2019-01-24
利用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;
}
}
}
附Jcrop的引數、API說明文件:
引數:
名稱 | 預設值 | 說明 |
---|---|---|
allowSelect | true | 允許新選框 |
allowMove | true | 允許選框移動 |
allowResize | true | 允許選框縮放 |
trackDocument | true | |
baseClass | "jcrop" | 基礎樣式名字首。說明:class="jcrop-holder",更改的只是其中的 jcrop。 |
addClass | null | 新增樣式會。例:假設值為 "test",那麼會新增樣式到 class="test jcrop-holder" |
bgColor | "black" | 背景顏色。顏色關鍵字、HEX、RGB 均可。 |
bgOpacity | 0.6 | 背景透明度 |
bgFade | false | 使用背景過渡效果 |
borderOpacity | 0.4 | 選框邊框透明度 |
handleOpacity | 0.5 | 縮放按鈕透明度 |
handleSize | 9 | 縮放按鈕大小 |
handleOffset | 5 | 縮放按鈕與邊框的距離 |
aspectRatio | 0 | 選框寬高比。說明:width/height |
keySupport | true | 支援鍵盤控制。按鍵列表:上下左右(移動)、Esc(取消)、Tab(跳出裁剪框,到下一個) |
cornerHandles | true | 允許邊角縮放 |
sideHandles | true | 允許四邊縮放 |
drawBorders | true | 繪製邊框 |
dragEdges | true | 允許拖動邊框 |
fixedSupport | true | |
touchSupport | null | |
boxWidth | 0 | 畫布寬度 |
boxHeight | 0 | 畫布高度 |
boundary | 2 | 邊界。說明:可以從邊界開始拖動滑鼠選擇裁剪區域 |
fadeTime | 400 | 過度效果的時間 |
animationDelay | 20 | 動畫延遲 |
swingSpeed | 3 | 過渡速度 |
minSelect | [0,0] | 選框最小選擇尺寸。說明:若選框小於該尺寸,則自動取消選擇 |
maxSize | [0,0] | 選框最大尺寸 |
minSize | [0,0] | 選框最小尺寸 |
onChange | function(){} | 選框改變時的事件 |
onSelect | function(){} | 選框選定時的事件 |
onRelease | function(){} | 取消選框時的事件 |
API
名稱 | 說明 |
---|---|
setImage(string) | 設定(或改變)影象。例:jcrop_api.setImage("newpic.jpg") |
setOptions(object) | 設定(或改變)引數,格式與初始化設定引數一樣 |
setSelect(array) | 建立選框,引數格式為:[x,y,x2,y2] |
animateTo(array) | 用動畫效果建立選框,引數格式為:[x,y,x2,y2] |
release() | 取消選框 |
disable() | 禁用 Jcrop。說明:已有選框不會被清除。 |
enable() | 啟用 Jcrop |
destroy() | 移除 Jcrop |
tellSelect() | 獲取選框的值(實際尺寸)。例子:console.log(jcrop_api.tellSelect()) |
tellScaled() | 獲取選框的值(介面尺寸)。例子:console.log(jcrop_api.tellScaled()) |
getBounds() | 獲取圖片實際尺寸,格式為:[w,h] |
getWidgetSize() | 獲取圖片顯示尺寸,格式為:[w,h] |
getScaleFactor() | 獲取圖片縮放的比例,格式為:[w,h] |