ASP 例項:頭像上傳。檔案(圖片)上傳,頭像擷取(Jquery-ui外掛來選取擷取區域)
阿新 • • 發佈:2019-02-08
引入JS檔案:
<link href="../Css/themes/ui-lightness/jquery-ui-1.8.2.custom.css" rel="stylesheet" /> jquery-ui的css檔案
<script src="../js/jquery-1.7.1.js"></script> jquery的js檔案
<script src="../js/jquery-ui-1.8.2.custom.min.js"></script> jquery-ui的js檔案
<script src="../SWFUpload/swfupload.js"></script> 上傳檔案(圖片)外掛的js檔案
<script src="../SWFUpload/handlers.js"></script> 上傳檔案(圖片)外掛的js檔案
CutPhoto.aspx:
upload.ashx.cs:<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CutPhoto.aspx.cs" Inherits="BookShop.Web.Member.CutPhoto" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <link href="../Css/themes/ui-lightness/jquery-ui-1.8.2.custom.css" rel="stylesheet" /> <script src="../js/jquery-1.7.1.js"></script> <script src="../js/jquery-ui-1.8.2.custom.min.js"></script> <script src="../SWFUpload/swfupload.js"></script> <script src="../SWFUpload/handlers.js"></script> <script type="text/javascript"> var swfu; window.onload = function() { swfu = new SWFUpload({ // Backend Settings upload_url: "/ashx/upload.ashx?action=upload", post_params: { "ASPSESSID": "<%=Session.SessionID %>" }, // File Upload Settings file_size_limit: "2 MB", file_types: "*.jpg;*.gif", file_types_description: "JPG Images", file_upload_limit: 0, // Zero means unlimited // Event Handler Settings - these functions as defined in Handlers.js // The handlers are not part of SWFUpload but are part of my website and control how // my website reacts to the SWFUpload events. swfupload_preload_handler: preLoad, swfupload_load_failed_handler: loadFailed, file_queue_error_handler: fileQueueError, file_dialog_complete_handler: fileDialogComplete, upload_progress_handler: uploadProgress, upload_error_handler: uploadError, upload_success_handler: showImage, upload_complete_handler: uploadComplete, // Button settings button_image_url: "/SWFUpload/images/XPButtonNoText_160x22.png", button_placeholder_id: "spanButtonPlaceholder", button_width: 160, button_height: 22, button_text: '<span class="button">請選擇上傳圖片<span class="buttonSmall">(2 MB Max)</span></span>', button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }', button_text_top_padding: 1, button_text_left_padding: 5, // Flash Settings flash_url: "/SWFUpload/swfupload.swf", // Relative to this file flash9_url: "/SWFUpload/swfupload_FP9.swf", // Relative to this file custom_settings: { upload_target: "divFileProgressContainer" }, // Debug Settings debug: false }); } //上傳成功以後呼叫該方法 function showImage(file, serverData) { // $("#showPhoto").attr("src", serverData); var data = serverData.split(':'); //將上傳成功的圖片作為DIV(#divContent)的背景 $("#hiddenImageUrl").val(data[0]); //將上傳成功的圖片路徑儲存到隱藏域中。 $("#divContent").css("backgroundImage", "url('" + data[0] + "')").css("width", data[1] + "px").css("height", data[2] + "px"); } $(function() { //讓擷取圖片的DIV(#divCut)可以移動與拖動大小(jquery-ui) $("#divCut").draggable({ containment: "#divContent", scroll: false }).resizable({ containment: "#divContent" }); $("#btnCut").click(function() { cutPhoto(); }); }) //擷取頭像 function cutPhoto() { //計算要擷取的頭像的範圍。 var y = $("#divCut").offset().top - $("#divContent").offset().top; //縱座標 var x = $("#divCut").offset().left - $("#divContent").offset().left; var width = $("#divCut").width(); var heigth = $("#divCut").height(); var pars = { "x": x, //擷取的圖片相對於原圖的偏移量 "y": y, "width": width, //擷取的圖片的長寬 "height": heigth, "action": "cut", "imgSrc": $("#hiddenImageUrl").val() }; //JSON格式的引數。 圖片的擷取是在伺服器端,服務端在原圖的基礎上擷取,客戶端只傳遞擷取圖片的座標引數。 $.post("/ashx/upload.ashx", pars, function(data) { $("#showPhoto").attr("src", data); //將擷取後的圖片顯示在(#showPhoto)中。 }); } </script> </head> <body> <form id="form1" runat="server"> <div id="content"> <div id="swfu_container" style="margin: 0px 10px;"> <div> <span id="spanButtonPlaceholder"></span> </div> <div id="divFileProgressContainer" style="height: 75px;"><!--上傳進度條的提示--></div> <div id="thumbnails"> </div> <div id="divContent" style="width: 300px; height: 300px;"> <!--顯示原圖(大圖)的div--> <div id="divCut" style="width: 100px; height: 100px; border: solid red 1px"> </div> <!--擷取小圖的div--> </div> <input type="button" value="擷取圖片" id="btnCut" /> <input type="hidden" id="hiddenImageUrl" /> <!--用於儲存和傳遞伺服器端的原圖(大圖)的相對路徑--> <img id="showPhoto" /> <!--擷取並上傳成功後,從伺服器返回擷取後的圖片--> </div> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Web; namespace BookShop.Web.ashx { /// <summary> /// upload 的摘要說明 /// </summary> public class upload : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string action = context.Request["action"]; if (action == "upload")//上傳原圖片(大圖) { ProcessFileUpload(context); } else if (action =="cut")//擷取圖片(小圖) { ProcessCutPhoto(context); } else { context.Response.Write("引數錯誤!!"); } } /// <summary> /// 檔案(原圖,大圖)上傳 /// </summary> /// <param name="context"></param> private void ProcessFileUpload(HttpContext context) { HttpPostedFile file = context.Request.Files["Filedata"]; if (file != null) { string fileName = Path.GetFileName(file.FileName); string fileExt = Path.GetExtension(fileName); if (fileExt == ".jpg") { string dir = "/ImageUpload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/"; if (!Directory.Exists(context.Request.MapPath(dir))) { Directory.CreateDirectory(context.Request.MapPath(dir)); } string newfileName = Guid.NewGuid().ToString(); string fullDir = dir + newfileName + fileExt; file.SaveAs(context.Request.MapPath(fullDir)); using (Image img = Image.FromFile(context.Request.MapPath(fullDir))) { context.Response.Write(fullDir + ":" + img.Width + ":" + img.Height); } //file.SaveAs(context.Request.MapPath("/ImageUpload/"+fileName)); //context.Response.Write("/ImageUpload/" + fileName); } } } /// <summary> /// 圖片的擷取 /// </summary> /// <param name="context"></param> private void ProcessCutPhoto(HttpContext context) { int x = Convert.ToInt32(context.Request["x"]); //擷取的圖片相對於原圖的偏移量 int y = Convert.ToInt32(context.Request["y"]); int width = Convert.ToInt32(context.Request["width"]); //擷取的圖片的長寬 int height = Convert.ToInt32(context.Request["height"]); string imgSrc = context.Request["imgSrc"]; //通過客戶端隱藏域獲取上傳成功的原圖(大圖)的路徑 using (Bitmap map = new Bitmap(width, height)) { using (Graphics g = Graphics.FromImage(map)) { using (Image img = Image.FromFile(context.Request.MapPath(imgSrc))) { //第一個引數:表示畫哪張圖片。 //完成圖片的擷取 //二:畫多麼大。 //三:畫原圖的哪塊區域 (x,y表示偏移量,width和height表示擷取的圖片的大小) g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel); //擷取圖片 string newfileName = Guid.NewGuid().ToString(); string fullDir = "/ImageUpload/" + newfileName + ".jpg"; map.Save(context.Request.MapPath(fullDir),System.Drawing.Imaging.ImageFormat.Jpeg); //儲存擷取後的圖片。 context.Response.Write(fullDir); //在客戶端回顯擷取後的圖片。 } } } } public bool IsReusable { get { return false; } } } }