“上傳圖片到服務器”之SWFUpload與imgAreaSelect的使用----實現切圖效果

一、將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" οnclick="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~~~~~~











發佈了32 篇原創文章 · 獲贊 7 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章