zoukankan      html  css  js  c++  java
  • 周末大放送网站图片上传,水印,预览,截图

        周末闲着没事,将网站中经常用到的对图片的操作做了一个总结,方便以后回顾,这里将一天的成果,贴出来,希望能帮到大家。

        首先是swfupload方式的无刷新上传,关于怎么配置,按照demo 的写法,我相信只要你不是太笨,都能成功。

        关于swfupload你可以去网上下,也可以点这里下载:SWFUpload_v250_beta_3_samples.rar

       项目结构:

                

    上传代码:

    前台上传页面,你可以根据需要建html页,也可以建webform。这里用一般处理程序来对照片进行处理,加水印,修改文件名等操作。

     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_ 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>
    SWFUploadImage.aspx
     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 }
    SWFUploadHandler.ashx

    预览和截图,水印代码(这里将他们整合在一个页面了,实在不想再建页面,在配置swfupload),截图的时候,用到网上的一个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_ 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=" 300px; height: 300px">
    112             <div id="divCut" style="height: 100px;  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>
    CutPhoto.aspx
      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 }
    CutPhoto.ashx

    其实对照片的操作还有生成缩略图,我想着图片上传后,就是对照片按比例缩放,这里就不再赘述了。其实在总结的时候,遇到最让人DT的就是uploadify这个上传插件,也不知道什么地方设置错了,能上传成功,但就是不能触发事件,这里也将代码贴出来,有知道的大神,一定告诉我,这代码很折腾人啊。

    这可能也是我选择swfupload放弃uploadify的原因,不能触发上传成功的事件,获取不到上传成功的图片的路径。

    解决方案:

    代码:

     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照片上传,预览,截图,水印

  • 相关阅读:
    各系统终端快速清屏方式
    mvc使用Chsword.Excel2Object导出和导入数据
    winfrom读写txt文件值(短信猫)
    WebDatagrid中添加打开新tab的超链接列
    WebDatagrid前台后台选中行
    WebDatagrid三种获取值得方法javascript
    WebDataMenu做工具栏程序代码
    WebDatagrid-checkbox行如何用js控制其是否可用
    WebDatagrid-左边的checkbox决定右边的文本是否进入编辑状态
    Cell Editing (WebDataGrid) 单元格编辑
  • 原文地址:https://www.cnblogs.com/wolf-sun/p/3266151.html
Copyright © 2011-2022 走看看