使用GDI对SWFUpload上传的图片进行截取头像

时间:2021-12-18 04:11:02

看此文章之前先看 SWFUpload异步上传图像 

GDI对图像的处理能力非常强大 相当繁琐复杂 我们这次会用到关于处理IMG的一些用法

这次会用到 JqueryUI 完成一下Div的拖动和改变大小

 可以到JqueryUI官网下载即可

 SWFUpload基础上传就不细讲了上一篇随笔里有说到

 首先实例SWFUpload对象

 1 var swfu;
 2         window.onload = function () {
 3             swfu = new SWFUpload({
 4                 // Backend Settings
 5                 upload_url: "Ashx/CutPhoto.Ashx?action=up",
 6                 post_params: {
 7                     "ASPSESSID": "<%=Session.SessionID %>"
 8                 },
 9 
10                 // File Upload Settings
11                 file_size_limit: "4 MB",
12                 file_types: "*.jpg;*.gif;*.png",
13                 file_types_description: "JPG Images",
14                 file_upload_limit: 0,    // Zero means unlimited
15 
16                 // Event Handler Settings - these functions as defined in Handlers.js
17                 //  The handlers are not part of SWFUpload but are part of my website and control how
18                 //  my website reacts to the SWFUpload events.
19                 swfupload_preload_handler: preLoad,
20                 swfupload_load_failed_handler: loadFailed,
21                 file_queue_error_handler: fileQueueError,
22                 file_dialog_complete_handler: fileDialogComplete,
23                 upload_progress_handler: uploadProgress,
24                 upload_error_handler: uploadError,
25                 //上传完成 uploadSuccess
26                 upload_success_handler: ShowData,
27                 upload_complete_handler: uploadComplete,
28 
29                 // Button settings
30                 button_image_url: "SWFUpLoad/images/XPButtonNoText_160x22.png",
31                 button_placeholder_id: "spanButtonPlaceholder",
32                 button_width: 160,
33                 button_height: 22,
34                 button_text: '<span class="button">Select Images <span class="buttonSmall">(4 MB Max)</span></span>',
35                 button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
36                 button_text_top_padding: 1,
37                 button_text_left_padding: 5,
38 
39                 // Flash Settings
40                 flash_url: "SWFUpLoad/swfupload.swf",    // Relative to this file
41                 flash9_url: "SWFUpLoad/swfupload_FP9.swf",    // Relative to this file
42 
43                 custom_settings: {
44                     upload_target: "divFileProgressContainer"
45                 },
46 
47                 // Debug Settings
48                 debug: false
49             });
50         }

必要的Html

 1 <body>
 2     <div id="content">
 3         <div id="swfu_container" style="margin: 0px 10px;">
 4             <div>
 5                 <span id="spanButtonPlaceholder"></span>
 6             </div>
 7             <div id="divFileProgressContainer" style="height: 75px"></div>
 8             <div id="divContent" style="width: 300px; height: 300px">
 9                 <div id="divCut" style="width: 100px; height: 100px; border: dashed 1px #f00"></div>
10             </div>
11         </div>
12         <div>
13             <input type="button" value="截取头像" id="btnCut" />
14         </div>
15         <img id="imgSrc" />
16     </div>
17 </body>

这里 divContent用于显示上传成功的图像 divCut用于截取

JqueryUI渲染截取Div可拖动和改变大小

1 $("#divCut").draggable({ containment: 'parent' }).resizable({ containment: '#divContent' });

渲染后效果图如下

使用GDI对SWFUpload上传的图片进行截取头像

要截取头像就必须确定两个矩形

1.原图像矩形(这个可以通过服务端通过文件流确定)

2.要截取的矩形大小和位置(主要) y 为据浏览器顶端的位置 x 为浏览器据左端的位置

 确定数据异步发送

 1 $(function () {
 2              
3
//确定要截取的范围 4 $("#btnCut").click(function () { 5 // offset 获取元素的绝对坐标 6 var y = $("#divCut").offset().top - $("#divContent").offset().top;//纵坐标 7 var x = $("#divCut").offset().left - $("#divContent").offset().left;//横坐标 8 var width = $("#divCut").width();//宽度 9 var height = $("#divCut").height();//高度 10 //将截取的数据发到服务端做处理 11 $.post("Ashx/CutPhoto.Ashx", { 12 "action": "cut", 13 "x": parseInt(x), 14 "y": parseInt(y), 15 "width": parseInt(width), 16 "height": parseInt(height), 17 "imgSrc": d[1] 18 }, function (data) { 19 $("#imgSrc").attr("src", data); 20 }); 21 }); 22 });

定义一般处理程序处理图片 处理图像的一些细节原理写在注释里

因为所显示图片的Div里面要在放个Div进行完成截取 所以这里一半处理程序 需要回发 图片的宽高 (上传时)

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Drawing;
 4 using System.IO;
 5 using System.Linq;
 6 using System.Web;
 7 
 8 namespace SWFUpLoad.Ashx
 9 {
10     /// <summary>
11     /// CutPhoto 的摘要说明
12     /// </summary>
13     public class CutPhoto : IHttpHandler
14     {
15 
16         public void ProcessRequest(HttpContext context)
17         {
18             context.Response.ContentType = "text/plain";
19             //判断操作
20             string action = context.Request["action"];
21             if (action.Equals("up"))//上传
22             {
23                 HttpPostedFile file = context.Request.Files["Filedata"];//接收文件
24                 string fileName = Path.GetFileName(file.FileName);//获取文件名
25                 string FileExt = Path.GetExtension(fileName);//获取文件类型
26                 if (FileExt == ".jpg" || FileExt == ".png" || FileExt == ".JPG")
27                 {
28                     //通过文件流 或者物理路径 创建Image实体
29                     using (Image img = Image.FromStream(file.InputStream))
30                     {
31                         string imgSrc = DateTime.Now.ToString("yyyyMMddHHmmss") + FileExt;
32                         file.SaveAs(context.Server.MapPath("/UploadPhoto/" + imgSrc));
33                         context.Response.Write("ok:/UploadPhoto/" + imgSrc + ":" + img.Width + ":" + img.Height);
34                     }
35                 }
36             }
37             else if (action.Equals("cut"))//头像截取
38             {
39                 //接收数据
40                 int x = Convert.ToInt32(context.Request.Form["x"]);
41                 int y = Convert.ToInt32(context.Request.Form["y"]);
42                 int width = Convert.ToInt32(context.Request.Form["width"]);
43                 int height = Convert.ToInt32(context.Request.Form["height"]);
44                 string imgSrc = context.Request.Form["imgSrc"];//接受保存的图片
45                 //将传递过来的范围,画在画布上,在保存画布
46                 using (Bitmap map = new Bitmap(width, height))
47                 {
48                     //为画布创建画笔
49                     using (Graphics g = Graphics.FromImage(map))
50                     {
51                         //创建图片
52                         using (Image img = Image.FromFile(context.Server.MapPath(imgSrc)))
53                         {
54                             //第11的重载 将图片画到画布上
55                             //img 对哪张图片进行操作
56                             //Rectangle 画布大小
57                             //Rectangle 画的部分
58                             g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
59                             //定义图片名称
60                             string newimgSrc = DateTime.Now.ToString("yyyyMMddHHmmss") + "_Cut" + ".JPG";
61                             map.Save(context.Server.MapPath("/UploadPhoto/" + newimgSrc));
62                             context.Response.Write("/UploadPhoto/" + newimgSrc);
63                         }
64                     }
65                 }
66             }
67         }
68 
69         public bool IsReusable
70         {
71             get
72             {
73                 return false;
74             }
75         }
76     }
77 }

定义上传成功后的函数 这是显示上传后的图片 截取后的头像将会在$.ajax里面

1 var d;
2         //上传成功
3         function ShowData(file, serverData) { 4 d = serverData.split(":"); 5 if (d[0] == "ok") { 6 //$("#imgSrc").attr("src", d[1]); 7 $("#divContent").css("backgroundImage", "url(" + d[1] + ")").css("width", d[2] + "px").css("height", d[3] + "px"); 8  } 9 }

 注意这里 d 设为全局变量用于接收图片信息

使用GDI对SWFUpload上传的图片进行截取头像

OK! 截取成功