週末閒着沒事,將網站中常常用到的對圖片的操做作了一個總結,方便之後回顧,這裏將一天的成果,貼出來,但願能幫到你們。javascript
首先是swfupload方式的無刷新上傳,關於怎麼配置,按照demo 的寫法,我相信只要你不是太笨,都能成功。css
關於swfupload你能夠去網上下,也能夠點這裏下載:SWFUpload_v250_beta_3_samples.rarhtml
項目結構:前端
上傳代碼:java
前臺上傳頁面,你能夠根據須要建html頁,也能夠建webform。這裏用通常處理程序來對照片進行處理,加水印,修改文件名等操做。react
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SWFUploadImage.aspx.cs" Inherits="Wolfy.ImageWeb.SWFUploadImage" %> 2 3 <!DOCTYPE html> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head id="Head1" runat="server"> 7 <title></title> 8 <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> 9 <script src="../SWFUpload/swfupload.js" type="text/javascript"></script> 10 <script src="../SWFUpload/handlers.js" type="text/javascript"></script> 11 <script src="../Script/jquery-1.7.1.js"></script> 12 <script type="text/javascript"> 13 var swfu; 14 window.onload = function () { 15 swfu = new SWFUpload({ 16 // Backend Settings 17 upload_url: "/SWFUploadHandler.ashx",//交給通常處理程序來處理 18 post_params: { 19 "ASPSESSID": "<%=Session.SessionID %>" 20 }, 21 22 // File Upload Settings 23 file_size_limit: "2 MB", 24 file_types: "*.jpg;*.gif", 25 file_types_description: "JPG Images", 26 file_upload_limit: 0, // Zero means unlimited 27 28 // Event Handler Settings - these functions as defined in Handlers.js 29 // The handlers are not part of SWFUpload but are part of my website and control how 30 // my website reacts to the SWFUpload events. 31 swfupload_preload_handler: preLoad, 32 swfupload_load_failed_handler: loadFailed, 33 file_queue_error_handler: fileQueueError, 34 file_dialog_complete_handler: fileDialogComplete, 35 upload_progress_handler: uploadProgress, 36 upload_error_handler: uploadError, 37 upload_success_handler: Show,//這裏修改了方法的定義。 38 upload_complete_handler: uploadComplete, 39 40 // Button settings 41 button_image_url: "/SWFUpload/images/XPButtonNoText_160x22.png", 42 button_placeholder_id: "spanButtonPlaceholder", 43 button_width: 160, 44 button_height: 22, 45 button_text: '<span class="button">選擇上傳圖片 <span class="buttonSmall">(2 MB Max)</span></span>', 46 button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }', 47 button_text_top_padding: 1, 48 button_text_left_padding: 5, 49 50 // Flash Settings 51 flash_url: "/SWFUpload/swfupload.swf", // Relative to this file 52 flash9_url: "/SWFUpload/swfupload_FP9.swf", // Relative to this file 53 54 custom_settings: { 55 upload_target: "divFileProgressContainer" 56 }, 57 58 // Debug Settings 59 debug: false 60 }); 61 } 62 //上傳成功之後執行該方法 63 function Show(file, serverData) { 64 var s = serverData.split(':');//接收從服務端返回的數據,按照分號分隔 65 66 if (s[0] == "ok") { 67 $("#imgSrc").attr("src", s[1]); 68 } 69 } 70 </script> 71 </head> 72 <body> 73 <form id="form1" runat="server"> 74 75 <div id="content"> 76 77 <div id="swfu_container" style="margin: 0px 10px;"> 78 <div> 79 80 <span id="spanButtonPlaceholder"></span> 81 82 </div> 83 84 <div id="divFileProgressContainer" style="height: 75px;"></div> 85 86 <img id="imgSrc" /> 87 </div> 88 </div> 89 </form> 90 </body> 91 </html>
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 Wolfy.ImageWeb 9 { 10 /// <summary> 11 /// SWFUploadHandler 的摘要說明 12 /// </summary> 13 public class SWFUploadHandler : IHttpHandler 14 { 15 16 public void ProcessRequest(HttpContext context) 17 { 18 context.Response.ContentType = "text/plain"; 19 HttpPostedFile file = context.Request.Files["Filedata"];//獲取上傳的文件數據. 20 string fileName = Path.GetFileName(file.FileName);//獲取上傳文件的名稱. 21 string fileExt = Path.GetExtension(fileName);//獲得文件的擴展名. 22 23 if (fileExt == ".jpg") 24 { 25 //將上傳的圖片放到不一樣的文件夾下.(根據日期) 26 string dir = "/UploadImage/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/"; 27 Directory.CreateDirectory(Path.GetDirectoryName(context.Server.MapPath(dir)));//建立文件夾. 28 //文件重命名名字 29 string fullDir = dir + DateTime.Now.ToString("yyyyMMddhhmmss") + fileExt;//構建完整的文件路徑. 30 file.SaveAs(context.Server.MapPath(fullDir)); 31 context.Response.Write("ok:" + fullDir); 32 33 34 } 35 } 36 37 public bool IsReusable 38 { 39 get 40 { 41 return false; 42 } 43 } 44 } 45 }
預覽和截圖,水印代碼(這裏將他們整合在一個頁面了,實在不想再建頁面,在配置swfupload),截圖的時候,用到網上的一個jquery插件(可變層,可移動層)jquery
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CutPhoto.aspx.cs" Inherits="Wolfy.ImageWeb.CutPhoto1" %> 2 3 <html xmlns="http://www.w3.org/1999/xhtml"> 4 <head id="Head1" runat="server"> 5 <title></title> 6 <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> 7 <script src="../SWFUpload/swfupload.js" type="text/javascript"></script> 8 <script src="../SWFUpload/handlers.js" type="text/javascript"></script> 9 <script src="../Script/jquery-1.7.1.js"></script> 10 <script src="Script/jquery-ui-1.8.2.custom.min.js"></script> 11 <script type="text/javascript"> 12 var swfu; 13 window.onload = function () { 14 swfu = new SWFUpload({ 15 // Backend Settings 16 upload_url: "/CutPhoto.ashx?action=up",//交給通常處理程序來處理 17 post_params: { 18 "ASPSESSID": "<%=Session.SessionID %>" 19 }, 20 21 // File Upload Settings 22 file_size_limit: "2 MB", 23 file_types: "*.jpg;*.gif", 24 file_types_description: "JPG Images", 25 file_upload_limit: 0, // Zero means unlimited 26 27 // Event Handler Settings - these functions as defined in Handlers.js 28 // The handlers are not part of SWFUpload but are part of my website and control how 29 // my website reacts to the SWFUpload events. 30 swfupload_preload_handler: preLoad, 31 swfupload_load_failed_handler: loadFailed, 32 file_queue_error_handler: fileQueueError, 33 file_dialog_complete_handler: fileDialogComplete, 34 upload_progress_handler: uploadProgress, 35 upload_error_handler: uploadError, 36 upload_success_handler: Show,//這裏修改了方法的定義。 37 upload_complete_handler: uploadComplete, 38 39 // Button settings 40 button_image_url: "/SWFUpload/images/XPButtonNoText_160x22.png", 41 button_placeholder_id: "spanButtonPlaceholder", 42 button_width: 160, 43 button_height: 22, 44 button_text: '<span class="button">選擇上傳圖片 <span class="buttonSmall">(2 MB Max)</span></span>', 45 button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }', 46 button_text_top_padding: 1, 47 button_text_left_padding: 5, 48 49 // Flash Settings 50 flash_url: "/SWFUpload/swfupload.swf", // Relative to this file 51 flash9_url: "/SWFUpload/swfupload_FP9.swf", // Relative to this file 52 53 custom_settings: { 54 upload_target: "divFileProgressContainer" 55 }, 56 57 // Debug Settings 58 debug: false 59 }); 60 } 61 var s; 62 //上傳成功之後執行該方法 63 function Show(file, serverData) { 64 s = serverData.split(':');//接收從服務端返回的數據,按照分號分隔 65 66 if (s[0] == "ok") { 67 //將服務端返回的圖片路徑做爲外層DIV的背景。 68 //注意:backgroundImage:I要大寫,url: 69 $("#divContent").css("backgroundImage", "url(" + s[1] + ")").css("width", s[2] + "px").css("height", s[3] + "px");//注意單位必定要加上 70 } 71 } 72 //截圖 73 $(function () { 74 $("#divCut").resizable({ 75 containment: '#divContent' 76 }).draggable({ containment: 'parent' }); 77 $("#btnCut").click(function () { 78 //開始獲取divCut的範圍 79 //offset():表示元素相對瀏覽器的相對座標. 80 var y = $("#divCut").offset().top - $("#divContent").offset().top; //獲得縱座標. 81 var x = $("#divCut").offset().left - $("#divContent").offset().left; 82 var width = $("#divCut").width(); //寬度 83 var height = $("#divCut").height(); //高度. 84 $.post("/CutPhoto.ashx", { "action": "cut", "x": parseInt(x), "y": parseInt(y), "width": parseInt(width), "height": parseInt(height), "imgSrc": s[1] }, function (data) { 85 $("#cutPhotoSrc").attr("src", data); 86 }); 87 }); 88 //打水印並預覽 89 $("#waterPhoto").click(function () { 90 $.post("/CutPhoto.ashx", {"action":"water","imgSrc":s[1]},function(data){ 91 $("#waterPhoto").attr("src", data); 92 }); 93 }); 94 }); 95 </script> 96 </head> 97 <body> 98 <form id="form1" runat="server"> 99 100 <div id="content"> 101 102 <div id="swfu_container" style="margin: 0px 10px;"> 103 <div> 104 <span id="spanButtonPlaceholder"></span> 105 </div> 106 107 <div id="divFileProgressContainer" style="height: 75px;"></div> 108 109 </div> 110 </div> 111 <div id="divContent" style="width: 300px; height: 300px"> 112 <div id="divCut" style="height: 100px; width: 100px; border: 1px solid red"></div> 113 </div> 114 <input type="button" id="btnCut" value="裁剪" /> 115 <input type="button" id="btnWater" value="水印" /> 116 <img id="cutPhotoSrc" /> 117 <img id="waterPhoto" /> 118 119 </form> 120 </body> 121 </html>
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 Wolfy.ImageWeb 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 string action = context.Request["action"]; 20 if (action == "up") 21 { 22 HttpPostedFile file = context.Request.Files["Filedata"];//獲取上傳的文件數據. 23 string fileName = Path.GetFileName(file.FileName);//獲取上傳文件的名稱. 24 string fileExt = Path.GetExtension(fileName);//獲得文件的擴展名. 25 26 if (fileExt == ".jpg") 27 { 28 using (Image img = Image.FromStream(file.InputStream))//根據上傳的圖片建立一個Image,獲取圖片的高度與寬度. 29 { 30 31 file.SaveAs(context.Server.MapPath("/UploadImage/" + fileName));//把圖片保存起來。 32 context.Response.Write("ok:/UploadImage/" + fileName + ":" + img.Width + ":" + img.Height);//將圖片路徑與圖片的高度與寬度返回瀏覽器 33 } 34 } 35 } 36 else if (action == "cut")//圖片截取. 37 { 38 39 //1接收參數. 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 //2:建立畫布 46 using (Bitmap map = new Bitmap(width, height))//將紅色DIV肯定範圍畫到畫布上 47 { 48 //3;畫筆 49 using (Graphics g = Graphics.FromImage(map)) 50 { 51 //4:用畫筆將圖片畫到畫布上 52 using (Image img = Image.FromFile(context.Server.MapPath(imgSrc))) 53 { 54 //1:指定的是對哪張圖片進行操做. 55 //2:指定畫多麼大。 56 //3:畫img的哪一部分. 57 g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel); 58 string newfileName = Guid.NewGuid().ToString().Substring(0, 8); 59 map.Save(context.Server.MapPath("/UploadImage/" + newfileName + ".jpg"));//保存截取後的圖片. 60 context.Response.Write("/UploadImage/" + newfileName + ".jpg"); 61 } 62 63 } 64 65 } 66 } 67 else if (action == "water") 68 { 69 string imgSrc = context.Request.Form["imgSrc"]; 70 //將照片做爲畫板 71 using (Image img = Image.FromFile(context.Server.MapPath(imgSrc))) 72 { 73 //3;畫筆 74 using (Graphics g = Graphics.FromImage(img)) 75 { 76 //4:用畫筆將字符串畫到畫布上 77 //1:指定的是對哪張圖片進行操做. 78 //2:指定畫多麼大。 79 //3:畫img的哪一部分. 80 g.DrawString("http://www.wolfy.com",new Font("華文行楷",30),new SolidBrush(Color.Red), new Rectangle(0, 0, img.Width, img.Height)); 81 string newfileName = Guid.NewGuid().ToString().Substring(0, 8); 82 img.Save(context.Server.MapPath("/UploadImage/" + newfileName + ".jpg"));//保存水印後的圖片. 83 context.Response.Write("/UploadImage/" + newfileName + ".jpg"); 84 } 85 } 86 // 87 // 88 //{ 89 // //4:用畫筆將圖片畫到畫布上 90 91 // { 92 // //1:指定的是對哪張圖片進行操做. 93 // //2:指定畫多麼大。 94 // //3:畫img的哪一部分. 95 // g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel); 96 // string newfileName = Guid.NewGuid().ToString().Substring(0, 8); 97 // map.Save(context.Server.MapPath("/UploadImage/" + newfileName + ".jpg"));//保存截取後的圖片. 98 // context.Response.Write("/UploadImage/" + newfileName + ".jpg"); 99 100 101 102 } 103 } 104 105 public bool IsReusable 106 { 107 get 108 { 109 return false; 110 } 111 } 112 } 113 }
其實對照片的操做還有生成縮略圖,我想着圖片上傳後,就是對照片按比例縮放,這裏就再也不贅述了。其實在總結的時候,遇到最讓人DT的就是uploadify這個上傳插件,也不知道什麼地方設置錯了,能上傳成功,但就是不能觸發事件,這裏也將代碼貼出來,有知道的大神,必定告訴我,這代碼很折騰人啊。web
這可能也是我選擇swfupload放棄uploadify的緣由,不能觸發上傳成功的事件,獲取不到上傳成功的圖片的路徑。瀏覽器
解決方案:jquery插件
代碼:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title></title> 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 6 <script src="/uploadify/jquery-1.7.2.min.js" type="text/javascript"></script> 7 <!--<script src="/uploadify/jquery.uploadify-3.1.min.js" type="text/javascript"></script>--> 8 <script src="uploadify/jquery.uploadify.min.js"></script> 9 <link href="/uploadify/uploadify.css" rel="stylesheet" type="text/css" /> 10 <script type="text/javascript"> 11 $(document).ready(function () { 12 //.uploadify()方法建立Uploadify上傳組件的一個實例。 13 $('#file_upload').uploadify({ 14 'auto': false, //關閉自動上傳 15 'removeTimeout': 1, //文件隊列上傳完成1秒後刪除 16 'swf': '/uploadify/uploadify.swf', 17 'uploader': '/uploadify/Uploadify.ashx', 18 'method': 'post', //方法,post仍是get提交 19 'buttonText': '瀏 覽', //設置按鈕文本 20 'multi': false, //容許同時上傳多張圖片 21 'uploadLimit': 10, //一次最多隻容許上傳10張圖片 22 'fileTypeDesc': 'Image Files', //只容許上傳圖像 23 'fileTypeExts': '*.gif; *.jpg; *.png;*.dwg', //限制容許上傳的圖片後綴 24 'fileSizeLimit': 2048000, //限制上傳的圖片不得超過2M 25 'onComplete': complete, 26 'onUploadSuccess': function (file, data, response) {//每次成功上傳後執行的回調函數,從服務端返回數據到前端 27 $('#' + file.id).find('.data').html(' 上傳完畢'); 28 }, 29 30 'onError': error 31 32 33 }); 34 35 }); 36 function complete(event, queueID, fileObj, response, data) { 37 alert(123); 38 }; 39 function error(event, queueID, fileObj) { 40 alert("文件:" + fileObj.name + " 上傳失敗"); 41 } 42 </script> 43 </head> 44 <body> 45 <div id="fileQueue"> 46 </div> 47 <input id="file_upload" name="file_upload" type="file" /> 48 <p> 49 <span style="color: Red; font-size: small;">最多一次上傳<b id="aLimit">10</b>張圖片</span><br /> 50 <a href="javascript:$('#file_upload').uploadify('settings', 'formData', {'typeCode':document.getElementById('id_file').value});$('#file_upload').uploadify('upload','*')">上傳</a> <a href="javascript:$('#file_upload').uploadify('cancel','*')">重置上傳隊列</a> 51 </p> 52 <input type="hidden" value="1215154" name="tmpdir" id="id_file" /> 53 <div id="showImg"> 54 <img src="#" alt="" id="image" /> 55 </div> 56 </body> 57 </html>
通常處理程序代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Web; 6 7 8 namespace UploadifyAndWatermark.uploadify 9 { 10 /// <summary> 11 /// Uploadify 的摘要說明 12 /// </summary> 13 public class Uploadify : IHttpHandler 14 { 15 16 public void ProcessRequest(HttpContext context) 17 { 18 context.Response.ContentType = "text/plain"; 19 context.Response.Charset = "utf-8"; 20 //接收上傳的文件 21 HttpPostedFile file = context.Request.Files["Filedata"]; 22 23 if (file != null) 24 { 25 string fileName = Path.GetFileName(file.FileName);//獲取上傳文件的名稱. 26 string fileExt = Path.GetExtension(fileName);//獲得文件的擴展名. 27 28 //將上傳的圖片放到不一樣的文件夾下.(根據日期) 29 string dir = "/UploadImage/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/"; 30 Directory.CreateDirectory(Path.GetDirectoryName(context.Server.MapPath(dir)));//建立文件夾. 31 //文件重命名名字 用當前時間做爲新名字 保存在相應的日期文件夾下 32 string fullDir = dir + DateTime.Now.ToString("yyyyMMddhhmmss") + fileExt;//構建完整的文件路徑. 33 //保存圖片 34 file.SaveAs(context.Server.MapPath(fullDir)); 35 //將圖片的路徑返回context.Resopnse.Write(fullDir); 36 context.Response.Write("1"); 37 38 } 39 else 40 { 41 context.Response.Write("0"); 42 } 43 44 } 45 46 47 public bool IsReusable 48 { 49 get 50 { 51 return false; 52 } 53 } 54 } 55 }
這裏將代碼展開,方便看到的大神,知道什麼緣由的,不要吝嗇你的一點點點點時間,拯救一下我這個爲代碼瘋狂的小白,不勝感激!
問題:在uploadify上傳成功後,爲何不觸發oncompelete事件?
是否上傳成功後的路徑能夠 context.Response.Write(路徑);在oncompelete事件參數中response能獲取到該路徑?
Demo下載:
Wolfy.UploadifyAndWatermark.rar uploadify照片上傳
Wolfy.ImageOperation.rar swfuploadify照片上傳,預覽,截圖,水印