基于asp.net實(shí)現(xiàn)圖片在線上傳并在線裁剪功能
1、說(shuō)明
接上一篇文章asp.net uploadify實(shí)現(xiàn)多附件上傳功能完成后,又突然用到頭像上傳并在線裁剪。在網(wǎng)上找個(gè)眾多例子都沒(méi)有符合要求的,有一篇文章寫的不錯(cuò),Asp.Net平臺(tái)下的圖片在線裁剪功能的實(shí)現(xiàn)代碼(源碼打包),大家可以看下
2、組成
首先說(shuō)明一下代碼實(shí)現(xiàn)所用到的技術(shù),僅供參考:
開(kāi)發(fā)工具:vs2010
目標(biāo)框架:.NET Framework3.5
jcrop:Jcrop.js v0.9.12
Uploadify:uploadify-v3.1
Jquery:jquery-1.9.0.js
最后我會(huì)將整個(gè)Demo上傳,如果同學(xué)們的電腦上有開(kāi)發(fā)環(huán)境可直接打開(kāi)項(xiàng)目解決方案運(yùn)行。
3、代碼
Default.aspx(測(cè)試頁(yè)面)


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ImgJcrop._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 runat="server">
<title>在線裁剪</title>
<link href="Scripts/jcrop/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
<link href="Scripts/uploadify-v3.1/uploadify.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery.1.9.0.min.js" type="text/javascript"></script>
<script src="Scripts/jcrop/jquery.Jcrop.js" type="text/javascript"></script>
<script src="Scripts/uploadify-v3.1/jquery.uploadify-3.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var jcrop_api, boundx, boundy;
$("#file_upload").uploadify({
"auto": true,
"buttonText": "選擇圖片",
"swf": "Scripts/uploadify-v3.1/uploadify.swf",
"uploader": "App_Handler/Uploadify.ashx?action=upload",
"fileTypeExts": "*.jpg; *.jpeg; *.gif; *.png; *.bmp",
"fileTypeDesc": "支持的格式:",
"multi": false,
"removeCompleted": false,
"onUploadStart": function (file) {
$("#file_upload-queue").hide();
},
"onUploadSuccess": function (file, data, response) {
var row = eval("[" + data + "]");
if (row[0]["status"] == 0) {
$("#cutimg").html("<img id=\"imgOriginal\" name=\"imgOriginal\" /><div style=\"overflow: hidden; margin-top: 20px;\"><div style=\"width: 120px; height: 120px; overflow: hidden;\"><img id=\"imgPreview\" /></div><br /><input type=\"button\" id=\"btnImgCut\" onclick=\"cutSaveImg()\" value=\"裁剪并保存圖片\" /></div>");
$("#cutimg img").each(function () { $(this).attr("src", row[0]["message"]); });
$("#hidImgUrl").val(row[0]["message"]);
$('#imgOriginal').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: 1,
//maxSize: [120, 120],
setSelect: [0, 0, 120, 120]
}, function () {
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
jcrop_api = this;
});
} else {
alert(row[0]["message"]);
}
}
});
function updatePreview(c) {
if (parseInt(c.w) > 0) {
var rx = 120 / c.w;
var ry = 120 / c.h;
$("#imgPreview").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"
});
}
$("#hidXone").val(c.x);
$("#hidYone").val(c.y);
$("#hidXtwo").val(c.hidXtwo);
$("#hidYtwo").val(c.hidYtwo);
$("#hidImgWidth").val(c.w);
$("#hidImgHeight").val(c.h);
};
});
function cutSaveImg() {
$.ajax({
type: "post",
url: "App_Handler/Uploadify.ashx?action=cutsaveimg",
data: { strImgUrl: $("#imgOriginal")[0].src, hidXone: $("#hidXone").val(), hidYone: $("#hidYone").val(), hidImgWidth: $("#hidImgWidth").val(), hidImgHeight: $("#hidImgHeight").val() },
dataType: "html",
success: function (data) {
var row = eval("[" + data + "]");
if (row[0]["status"] == 0) { }
alert(row[0]["message"]);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="file" id="file_upload" name="file_upload" />
</div>
<div id="cutimg">
</div>
<asp:HiddenField ID="hidXone" runat="server" />
<asp:HiddenField ID="hidYone" runat="server" />
<asp:HiddenField ID="hidXtwo" runat="server" />
<asp:HiddenField ID="hidYtwo" runat="server" />
<asp:HiddenField ID="hidImgWidth" runat="server" />
<asp:HiddenField ID="hidImgHeight" runat="server" />
<asp:HiddenField ID="hidImgUrl" runat="server" />
</form>
</body>
</html>
Uploadify.ashx(一般處理程序)
<%@ WebHandler Language="C#" Class="UploadifyUpload" %>
using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Linq;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.SessionState;
using System.IO;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
public class UploadifyUpload : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
string action = context.Request["action"];
switch (action)
{
case "upload":
//上傳圖片
upload(context);
break;
case "cutsaveimg":
//裁剪并保存
cutsaveimg(context);
break;
}
context.Response.End();
}
/// <summary>
/// 上傳圖片
/// </summary>
/// <param name="context"></param>
private void upload(HttpContext context)
{
HttpPostedFile postedFile = context.Request.Files["Filedata"];
if (postedFile != null)
{
string fileName, fileExtension;
int fileSize;
fileName = postedFile.FileName;
fileSize = postedFile.ContentLength;
if (fileName != "")
{
fileExtension = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
string strPath = context.Server.MapPath("/") + "\\App_File\\Upload\\";//設(shè)置文件的路徑
string strFileName = "upload" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtension;
string strFileUrl = strPath + strFileName;//保存文件路徑
if (!Directory.Exists(strPath))
{
Directory.CreateDirectory(strPath);
}
postedFile.SaveAs(strFileUrl);//先保存源文件
context.Response.Write("{\"status\":0,\"message\":\"/App_File/Upload/" + strFileName + "\"}");
}
else
{
context.Response.Write("{\"status\":1,\"message\":\"上傳失敗!\"}");
}
}
else
{
context.Response.Write("{\"status\":1,\"message\":\"上傳失敗!\"}");
}
}
/// <summary>
/// 裁剪并保存圖片
/// </summary>
/// <param name="context"></param>
private void cutsaveimg(HttpContext context)
{
string strImgUrl = context.Request["strImgUrl"];
string strXone = context.Request["hidXone"];
string strYone = context.Request["hidYone"];
string strImgWidth = context.Request["hidImgWidth"];
string strImgHeight = context.Request["hidImgHeight"];
string[] urls = strImgUrl.Split('/');
string str_url = urls.Last();
try
{
string strOldFiel = context.Server.MapPath("~/App_File/Upload/");
string strNewFiel = context.Server.MapPath("~/App_File/Cut/");
string strOldUrl = Path.Combine(strOldFiel, str_url);
string strNewUrl = Path.Combine(strNewFiel, "cut" + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + str_url.Split('.')[1]);
if (!Directory.Exists(strNewFiel))
{
Directory.CreateDirectory(strNewFiel);
}
int intStartX = int.Parse(strXone);
int intStartY = int.Parse(strYone);
int intWidth = int.Parse(strImgWidth);
int intHeight = int.Parse(strImgHeight);
CutGeneratedImage(intStartX, intStartY, intWidth, intHeight, strOldUrl, strNewUrl);
context.Response.Write("{\"status\":0,\"message\":\"裁剪成功并保存!\"}");
}
catch
{
context.Response.Write("{\"status\":1,\"message\":\"裁剪失?。"}");
}
}
/// <summary>
/// 裁剪圖片
/// </summary>
/// <param name="intWidth">要縮小裁剪圖片寬度</param>
/// <param name="intHeight">要縮小裁剪圖片長(zhǎng)度</param>
/// <param name="strOldImgUrl">要處理圖片路徑</param>
/// <param name="strNewImgUrl">處理完畢圖片路徑</param>
public void CutGeneratedImage(int intStartX, int intStartY, int intWidth, int intHeight, string strOldImgUrl, string strNewImgUrl)
{
//上傳標(biāo)準(zhǔn)圖大小
int intStandardWidth = 120;
int intStandardHeight = 120;
int intReduceWidth = 0; // 縮小的寬度
int intReduceHeight = 0; // 縮小的高度
int intCutOutWidth = 0; // 裁剪的寬度
int intCutOutHeight = 0; // 裁剪的高度
int level = 100; //縮略圖的質(zhì)量 1-100的范圍
//獲得縮小,裁剪大小
if (intStandardHeight * intWidth / intStandardWidth > intHeight)
{
intReduceWidth = intWidth;
intReduceHeight = intStandardHeight * intWidth / intStandardWidth;
intCutOutWidth = intWidth;
intCutOutHeight = intHeight;
}
else if (intStandardHeight * intWidth / intStandardWidth < intHeight)
{
intReduceWidth = intStandardWidth * intHeight / intStandardHeight;
intReduceHeight = intHeight;
intCutOutWidth = intWidth;
intCutOutHeight = intHeight;
}
else
{
intReduceWidth = intWidth;
intReduceHeight = intHeight;
intCutOutWidth = intWidth;
intCutOutHeight = intHeight;
}
//通過(guò)連接創(chuàng)建Image對(duì)象
//System.Drawing.Image oldimage = System.Drawing.Image.FromFile(strOldImgUrl);
//oldimage.Save(Server.MapPath("tepm.jpg"));
//oldimage.Dispose();
//縮小圖片
Bitmap bm = new Bitmap(strOldImgUrl);
//處理JPG質(zhì)量的函數(shù)
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo ici = null;
foreach (ImageCodecInfo codec in codecs)
{
if (codec.MimeType == "image/jpeg")
{
ici = codec;
break;
}
}
EncoderParameters ep = new EncoderParameters();
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)level);
//裁剪圖片
Rectangle cloneRect = new Rectangle(intStartX, intStartY, intCutOutWidth, intCutOutHeight);
PixelFormat format = bm.PixelFormat;
Bitmap cloneBitmap = bm.Clone(cloneRect, format);
//保存圖片
cloneBitmap.Save(strNewImgUrl, ici, ep);
bm.Dispose();
}
public bool IsReusable
{
get
{
return false;
}
}
}


4、最后奉上Demo
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
ASP.NET?Core中創(chuàng)建中間件的方式匯總
ASP.NET?Core中間件(Middleware)是用于處理HTTP請(qǐng)求和響應(yīng)的組件,它們被安排在請(qǐng)求處理管道中,并按順序執(zhí)行,這篇文章主要介紹了ASP.NET?Core中創(chuàng)建中間件的幾種方式,需要的朋友可以參考下2024-07-07
.net開(kāi)發(fā)人員常犯的錯(cuò)誤分析小結(jié)
我最新一直在和新手和入手級(jí)開(kāi)發(fā)人員打交道,我注意到一些開(kāi)發(fā)人員(甚至是老手)在粗心時(shí)常犯的錯(cuò)誤。這些錯(cuò)誤各不相同,從工具的使用到網(wǎng)絡(luò)服務(wù)的適當(dāng)應(yīng)用都有。以下是六個(gè)主要的開(kāi)發(fā)錯(cuò)誤。2009-03-03
ASP.NET中MVC使用AJAX調(diào)用JsonResult方法并返回自定義錯(cuò)誤信息
這篇文章主要介紹了ASP.NET中MVC使用AJAX調(diào)用JsonResult方法并返回自定義錯(cuò)誤信息的相關(guān)資料,需要的朋友可以參考下2014-11-11
調(diào)試ASP.NET應(yīng)用程序的方法和技巧
調(diào)試ASP.NET應(yīng)用程序的方法和技巧...2006-09-09
asp.net 無(wú)刷新附件上傳實(shí)現(xiàn)方法
一直以來(lái)附件上傳都是個(gè)很郁悶的問(wèn)題,剛開(kāi)始是利用js添加input file 然后一起提交來(lái)實(shí)現(xiàn)多文件上傳,在使用163郵箱的時(shí)候很是羨慕它的附件上傳部分(選擇完文件就提交,可以多個(gè)文件一起上傳,而且還可以獲取上傳進(jìn)度),這時(shí)就很想自己也寫個(gè)那樣的東西出來(lái)。2010-01-01
靈活掌握asp.net中g(shù)ridview控件的多種使用方法(上)
這篇文章向大家推薦如何靈活掌握asp.net中g(shù)ridview控件的多種使用方法,感興趣的小伙伴們可以參考一下2015-11-11
.NET/C#如何判斷某個(gè)類是否是泛型類型或泛型接口的子類型詳解
這篇文章主要給大家介紹了關(guān)于.NET/C#如何判斷某個(gè)類是否是泛型類型或泛型接口的子類型的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧2018-09-09

