您的位置:首页 > 编程语言 > C#

“上传图片到服务器”之SWFUpload与imgAreaSelect的使用----实现切图效果

2013-11-10 09:28 686 查看

一、将SWFUpload与imgAreaSelect一起配置至到项目中





imageareaselect网址:http://odyniec.net/projects/imgareaselect/usage.html

二、分别建立其它文件夹:Pages、JS、Tools、Handlers、Upload

Pages文件夹---------------用来存放静态或动态页面

JS文件夹--------------------用来存放JS文件

Tools文件夹----------------用来存放工具类

Handlers--------------------用来存放一般处理程序

Upload-----------------------用来存放上传成功后的文件

先配置服务器端,再配置前端

在Tools文件夹下新建一个MyTool类

public class MyTool
{
#region ISPicture是判断一个文件是不是图片
public static bool ISPicture(HttpPostedFile file)
{
bool result = false;
string[] exts = "bmp,jpg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw".Split(new char[] { ',' });
List<string> extList = new List<string>();
extList.AddRange(exts);
string ext = Path.GetExtension(file.FileName).Substring(1).ToLower();
if (extList.Contains(ext))
{
result = true;
}
return result;
}
#endregion

#region GetMD5拿一个流的MD5值
public static string GetMD5(Stream stream)
{
string result = string.Empty;
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] bytes = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sb.Append(bytes[i].ToString("X2"));
}
result = sb.ToString();
return result;
}
#endregion

#region 计算一个Image对象的md5值
       public static string GetMD5(Image img)
       {
          string result = string.Empty;
          using(MemoryStream ms=new MemoryStream())
          {
                //首先将Image对象转换为byte[]
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, (object)img);
                byte[] imgbytes = ms.ToArray();
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                byte[] bytes= md5.ComputeHash(imgbytes);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    sb.Append(bytes[i].ToString("X2"));
                }
                result = sb.ToString();
          }
          return result;
       }
       #endregion

#region CreateDirectory先去判断一个文件夹存不存在,如果不存在的话新建它
public static void CreateDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
#endregion
}


2、在Handlers文件夹中新建UploadFile.ashx

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
HttpPostedFile pfile = context.Request.Files["Filedata"];
//判断是不是图片
if (!MyTool.ISPicture(pfile))
{
return;
}

//准备新的文件名称,准备新的保存路径
string newfilename = MyTool.GetMD5(pfile.InputStream) + Path.GetExtension(pfile.FileName);
string newpath = "/Upload/" + DateTime.Now.ToString("yyyyMMdd");
MyTool.CreateDirectory(context.Request.MapPath(newpath));
string path = Path.Combine(context.Request.MapPath(newpath), newfilename);

//执行保存操作
pfile.SaveAs(path);
context.Response.Write("ok:" + newpath + "/" + newfilename);
}


3、在Pages文件夹中新建UploadFile.htm

HtmlCode

<div id="swfu-placeholder"><!--swfupload文件选择按钮占位符,执行下面的js后,这里将被替换成swfupload上传按钮--></div>
<span id="swfu-upload-status"><!--用来显示上传的信息---></span>
<div><input type="button" onclick="swfu.startUpload();" value="上传" /></div>

<img id="pimg" /><!--用来显示上传成功之后的图片-->

<input type="button" id="btnCut" value="剪切"/> <!--用来剪切图片的按钮-->
<img id="smallimg"/><!--用来显示剪切后的小图-->


JS

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
<script src="/swfu/swfupload.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function () {
InitSwfUpload();
}

function InitSwfUpload() {
var swfuOption = {//swfupload选项
upload_url: "/Handlers/UploadFile.ashx", //接收上传的服务端url
flash_url: "/swfu/Flash/swfupload.swf", //swfupload压缩包解压后swfupload.swf的url
button_placeholder_id: "swfu-placeholder", //
file_types: "*.jpg;*.jpeg;*.gif;*.png;*.bmp;", //类型
file_size_limit: "20480", //用户可以选择的文件大小,有效的单位有B、KB、MB、GB,若无单位默认为KB
button_width: 215, //按钮宽度
button_height: 45, //按钮高度
button_text: '<span class="btn-txt">选择文件</span>', //按钮文字
button_text_style: '.btn-txt{color: #666666;font-size:20px;font-family:"微软雅黑"}',
button_text_top_padding: 6,
button_text_left_padding: 65,
button_image_url: "/swfu/img/swfu_bgimg.jpg", //按钮背景图片路径
debug: true,
//事件
file_dialog_complete_handler: fileDialogComplete,
upload_progress_handler: uploadProgress,
upload_error_handler: uploadError, //文件上传出错
upload_success_handler: uploadSuccess, //文件上传成功
upload_complete_handler: uploadComplete//文件上传完成,在upload_error_handler或者upload_success_handler之后触发
};
var swfu = new SWFUpload(swfuOption); //初始化并将swfupload按钮替换swfupload占位符
}

function fileDialogComplete(selectedNum, queuedNum) {
if (queuedNum > 0) {//选择并添加到上传队列的文件数大于0
this.startUpload(); //开始上传
this.setButtonDisabled(true); //禁用上传按钮
}
}

function uploadProgress(file, curBytes, totalBytes) {
var statusE = document.getElementById('swfu-upload-status'); //文件上传进度节点
statusE.innerHTML = ['文件名:', file.name, '总尺寸:', totalBytes, 'B已上传:', curBytes, 'B进度:', parseInt((curBytes / totalBytes) * 100), '%'].join('');
}

//上传过程中出错
function uploadError(file, errCode, msg) {
statusE.innerHTML += ['文件[', file.name, ']上传出错,出错代码:[', errCode, '],出错原因:', msg].join('');
}

//上传成功
function uploadSuccess(file, data) {
//statusE.innerHTML += ['文件[', file.name, ']上传成功,服务器返回信息:', data].join('');
var d = data.split(':');
if (d[0] == 'ok') {
document.getElementById('pimg').setAttribute('src', d[1]);  //将上传成功后的图片显示在pimg中
}
}

//上传完成,无论上传过程中出错还是上传成功,都会触发该事件,并且在那两个事件后被触发
function uploadComplete(file) {
statusE.innerHTML += ['文件[', file.name, ']结束上传'].join('');
this.setButtonDisabled(false); //恢复上传按钮
}
</script>


此时可以正常上传图片到服务器,当上传成功后图片会显示在pimg中。

4、接下来就是使用imageAreaSelect进行截图的配置

引用js

<!--jquery-->
<script src="../JS/jquery-1.9.1.js" type="text/javascript"></script>

<!--jquery easyui之imgareaselect相关引用-->
<link href="../jquery.imgareaselect-0.9.10/css/imgareaselect-default.css" rel="stylesheet" type="text/css" />
<script src="../jquery.imgareaselect-0.9.10/scripts/jquery.imgareaselect.pack.js" type="text/javascript"></script>


修改uploadSuccess方法

var pimgpath;      //用来存放图片路径
var x = 0;         //剪切框横坐标
var y = 0;         //剪切框纵坐标
var width = 0;     //剪切框宽度
var height = 0;    //剪切框高度

//上传成功
function uploadSuccess(file, data) {
//statusE.innerHTML += ['文件[', file.name, ']上传成功,服务器返回信息:', data].join('');
var d = data.split(':');
if (d[0] == 'ok') {
pimgpath = d[1];
$('#pimg').attr('src', d[1]);
this.setButtonDisabled(false); //恢复上传按钮
$('#pimg').imgAreaSelect({
maxWidth: 200, maxHeight: 150, handles: true,
onSelectEnd: function (img, selection) {
x = selection.x1;
                   y = selection.y1;
                   width = selection.width;
                   height = selection.height;
}
});
$('#btnCut').click(function () {  //剪切按钮
                 //alert('图片路径:'+pimgpath+';x='+x+';y='+y+';width='+width+';height:'+height);
                 $.post('/Handlers/CutPhoto.ashx', { 'pimgpath': pimgpath, 'x': x, 'y': y, 'width': width, 'height': height }, function (data) {
                    if (typeof (data) != undefined && data != null && data != '') {
                         $('#smallimg').attr('src', data);
                    }
                 })
          });
}
}


5、在Handlers文件夹中新建CutPhoto.ashx

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//(1)接收原图路径、以及Cut的矩形在大图上的左标与该矩形的宽高
string pimgpath;
int x;
int y;
int width;
int height;
pimgpath =context.Request.Form["pimgpath"];
int.TryParse(context.Request.Form["x"],out x);
int.TryParse(context.Request.Form["y"], out y);
int.TryParse(context.Request.Form["width"],out width);
int.TryParse(context.Request.Form["height"],out height);
//(2)判断是否进行处理
if (string.IsNullOrEmpty(pimgpath) || x < 0 || y < 0 || width < 0 || height < 0)
{
return;
}
//(3)准备处理
using(Image img=Image.FromFile(context.Request.MapPath(pimgpath)))  //大图
{
using (Bitmap smallimg = new Bitmap(width, height))    //小图画布
{
using (Graphics g = Graphics.FromImage(smallimg))   //画笔
{
//开始使用画笔将要截取的图片画在画布上
//param1-----------原图对象
//param2-----------从原图中画多大
//param3-----------画原图中哪部分
//param4-----------单位
g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
//新的文件名称、保存路径、物理路径、并根据物理路径存在于否创建物理路径
string newfilename = MyTool.GetMD5(smallimg)+Path.GetExtension(pimgpath);
string newpath = "/Upload/" + DateTime.Now.ToString("yyyyMMdd");
string physicsnewpath = context.Request.MapPath(newpath);
MyTool.CreateDirectory(physicsnewpath);
//保存放件
string savepath = Path.Combine(physicsnewpath, newfilename);
smallimg.Save(savepath);
//返回其相对路径
context.Response.Write(newpath+"/"+newfilename);
}
}
}
}


OK~~~~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息