首页 > 网站 > WEB开发 > 正文

SWFUpload.js方法图片的上传和imgAreaselect.js方法图片任意部位的截取

2024-04-27 15:09:06
字体:
来源:转载
供稿:网友

SWFUpload.js方法图片的上传和imgAreaselect.js方法图片任意部位的截取

第一部分:图片上传                 1.创建c#web窗体                 2.添加SWFUpload.js的文件引用                      引用文件如下:    <script src="../Scripts/swfupload/swfupload.js"></script>                                                      <script src="../Scripts/swfupload/swfupload.queue.js"></script>                                                      <script src="../Scripts/js/handlers.js"></script>

                       注意:handlers.js的引用不放在其他2个引用文件夹下,放在同一个文件夹不知道出了什么错误。

                  3.添加选择图片按钮和显示图片布局

<body>    <form id="form1" runat="server">        <div><span id="spanButtonPlaceHolder"></span></div>        <div id="divFilePRogressContainer" style="height: 75px;"></div>        <img id="divphotoimage" />          </form></body>                   4.编写图片上传js代码
<script>  var swfu;        window.onload = function () {                                         swfu = new SWFUpload({                // Backend Settings                upload_url: "../Handler/test.ashx?cmd=upload",	//一般处理程序(带参数)                post_params: {                    "aspSESSID": "<%=session.SessionID %>"      //参数(不知道干嘛)                },                // File Upload Settings                file_size_limit: "2048",	// 2MB          //文件大小                file_types: "*.jpg",                            //类型                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.                file_queue_error_handler: fileQueueError,                          file_dialog_complete_handler: fileDialogComplete,                upload_progress_handler: uploadProgress,                upload_error_handler: uploadError,                upload_success_handler: showimage,               //图片显示成功的调用的方法,showimage是方法                upload_complete_handler: uploadComplete,                // Button settings                button_image_url: "../Scripts/js/images/XPButtonNoText_160x22.png", //选择图片按钮在这里设计                 button_width: "160",                button_height: "22",                button_placeholder_id: "spanButtonPlaceHolder",                     //在哪里显示(占位符)                button_text: '<span class="theFont">选择文件</span>',               //按钮显示文字内容                button_text_style: ".theFont { font-size: 13;}",                button_text_left_padding: 12,                button_text_top_padding: 3,                // Flash Settings                flash_url: "../Scripts/swfupload/swfupload.swf",	// Relative to this file  swfupload.swf需要添加到引用的文件夹下                custom_settings: {                    upload_target: "divFileProgressContainer"           //图片上传成功的信息内容                },                // Debug Settings                debug: false            });        }
        //图片上传成功后
        function showimage(file, serverData) {                 //serverData是一般处理程序返回的文件上传的图片路径            $("#divphotoimage").attr("src", serverData);                      }</script>

                        5.后台处理                         

    #region 上传图片

        private void fileuloadimage(HttpContext context)

        {

            HttpPostedFile file = context.Request.Files[0];

            string filename = Path.GetFileName(file.FileName);

            string fileXect = Path.GetExtension(filename);

            string filepath = context.Request.MapPath("/uploadimage/") + filename;

            file.SaveAs(filepath);

            context.Response.Write("/uploadimage/" + filename);

        }

        #endregion

                        6.SWFUpload.js的下载链接:http://pan.baidu.com/s/1mi8trVq 密码:xjbq

第二部分:图片截取

                            1、下载imgAreaselect.js 链接:http://pan.baidu.com/s/1eR2jFgA 密码:dcnr

                            2、 完整引用如下

                              <link href="../imgAreaSelect/imgareaselect-default.CSS" rel="stylesheet" />

    <script src="../Scripts/ui/jquery-1.4.2.js"></script>

    <script src="../imgAreaSelect/jquery.imgareaselect.min.js"></script>

    <script src="../Scripts/swfupload/swfupload.js"></script>

    <script src="../Scripts/swfupload/swfupload.queue.js"></script>

    <script src="../Scripts/js/handlers.js"></script>

3、界面布局

  <form id="form1" runat="server">        <div><span id="spanButtonPlaceHolder"></span></div>        <div id="divFileProgressContainer" style="height: 75px;"></div>        <img id="divphotoimage" />        <input id="imagecut" type="button" value="图像截取" />        <input type="hidden" id="imgsrc" />        <br />        <img id="cutnewimage" />    </form>4、图片上传成功后显示一个截取的图片框
 function showimage(file, serverData) {            $("#divphotoimage").attr("src", serverData);
            //将图片给了img后就会触发该事件,理解为创建一个div (0,0)左上角 (250,250)右下角 onSelectEnd为事件:选择要截图的图片后            $("#divphotoimage").imgAreaSelect({ selectionColor: 'bule', x1: 0, y1: 0, x2: 250, y2: 250, seclectionOpacity: 0.2, onSelectEnd: preview });            $("#imgsrc").val(serverData);  //将图片路径给隐藏域,在js里面最好不要使用全局变量,以后要用到图片路径        }5、图片截取成功后数据的保存
  function preview(img, selection) {
            //存取图片的x、y坐标和宽度高度            $("#divphotoimage").data('x', selection.x1);            $("#divphotoimage").data('y', selection.y1);            $("#divphotoimage").data('w', selection.width);            $("#divphotoimage").data('h', selection.height);        }6.参数的取出方法和传递给一般处理程序的方法
 $(function () {
            //点击图片截取按钮触发的事件            $("#imagecut").click(function () {
                var pars = {     //传递的参数                    x: $("#divphotoimage").data('x'),                    y: $("#divphotoimage").data('y'),                    width: $("#divphotoimage").data('w'),                    height: $("#divphotoimage").data('h'),                    imgsrc: $("#imgsrc").val(),                    cmd: "cut"                };                $.post("../Handler/test.ashx", pars, function (data) {  //一般处理程序请求的方法                    $("#cutnewimage").attr("src", data);                //将截取成功的图片显示出来                });            })        })7、后台将传递的参数也是就截取的图片画出来,保存起来

  #region 截取图片        private void cutuploadimage(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"];            Bitmap map = new Bitmap(width, height);        //创建画布            Graphics g = Graphics.FromImage(map);          //创建画笔            Image img = Image.FromFile(context.Request.MapPath(imgsrc)); //原始图片
            //将原图的指定范围画到画布上            //第一个img参数,表示对哪张图进行操作            //第二个参数,画多么大            //第三个参数,画多大的区域            //GraphicsUnit.Pixel像素单位 g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel); string filecutname = Guid.NewGuid().ToString(); string fullDir = "/uploadimage/" + filecutname + ".jpg"; map.Save(context.Request.MapPath(fullDir), System.Drawing.Imaging.ImageFormat.Jpeg); context.Response.Write(fullDir); } #endregion

       第三部分:完整的demo

         前台代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="text.aspx.cs" Inherits="ebook.Pages.text" %>

<!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="../imgAreaSelect/imgareaselect-default.css" rel="stylesheet" />

    <script src="../Scripts/ui/jquery-1.4.2.js"></script>

    <script src="../imgAreaSelect/jquery.imgareaselect.min.js"></script>

    <script src="../Scripts/swfupload/swfupload.js"></script>

    <script src="../Scripts/swfupload/swfupload.queue.js"></script>

    <script src="../Scripts/js/handlers.js"></script>

    <script>

        var swfu;

        window.onload = function () {

            swfu = new SWFUpload({

                // Backend Settings

                upload_url: "../Handler/test.ashx?cmd=upload",	// Relative to the SWF file

                post_params: {

                    "ASPSESSID": "<%=Session.SessionID %>"

                },

                // File Upload Settings

                file_size_limit: "2048",	// 2MB

                file_types: "*.jpg",

                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.

                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: "../Scripts/js/images/XPButtonNoText_160x22.png", // Relative to the Flash file

                button_width: "160",

                button_height: "22",

                button_placeholder_id: "spanButtonPlaceHolder",

                button_text: '<span class="theFont">选择文件</span>',

                button_text_style: ".theFont { font-size: 13;}",

                button_text_left_padding: 12,

                button_text_top_padding: 3,

                // Flash Settings

                flash_url: "../Scripts/swfupload/swfupload.swf",	// Relative to this file

                custom_settings: {

                    upload_target: "divFileProgressContainer"

                },

                // Debug Settings

                debug: false

            });

        }

        function showimage(file, serverData) {

            $("#divphotoimage").attr("src", serverData);

            $("#divphotoimage").imgAreaSelect({ selectionColor: 'bule', x1: 0, y1: 0, x2: 250, y2: 250, seclectionOpacity: 0.2, onSelectEnd: preview });

            $("#imgsrc").val(serverData);

        }

        //确定出要截取图像的方位数据参数

        function preview(img, selection) {

            $("#divphotoimage").data('x', selection.x1);

            $("#divphotoimage").data('y', selection.y1);

            $("#divphotoimage").data('w', selection.width);

            $("#divphotoimage").data('h', selection.height);

        }

        $(function () {

            $("#imagecut").click(function () {

                var pars = {

                    x: $("#divphotoimage").data('x'),

                    y: $("#divphotoimage").data('y'),

                    width: $("#divphotoimage").data('w'),

                    height: $("#divphotoimage").data('h'),

                    imgsrc: $("#imgsrc").val(),

                    cmd: "cut"

                };

                $.post("../Handler/test.ashx", pars, function (data) {

                    $("#cutnewimage").attr("src", data);

                });

            })

        })

    </script>

</head>

<body>

    <form id="form1" runat="server">

        <div><span id="spanButtonPlaceHolder"></span></div>

        <div id="divFileProgressContainer" style="height: 75px;"></div>

        <img id="divphotoimage" />

        <input id="imagecut" type="button" value="图像截取" />

        <input type="hidden" id="imgsrc" />

        <br />

        <img id="cutnewimage" />

    </form>

</body>

</html>

后台代码:

using System;using System.Collections.Generic;using System.Drawing;using System.Drawing.Drawing2D;using System.Drawing.Imaging;using System.IO;using System.Linq;using System.Web;namespace ebook.Handler{    /// <summary>    /// test 的摘要说明    /// </summary>    public class test : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            string str = context.Request["cmd"];            if (str == "upload")            {                fileuploadimage(context);            }            else if (str == "cut")            {                cutuploadimage(context);            }        }        #region 截取图片        private void cutuploadimage(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"];            Bitmap map = new Bitmap(width, height);            Graphics g = Graphics.FromImage(map);            Image img = Image.FromFile(context.Request.MapPath(imgsrc));            g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);            string filecutname = Guid.NewGuid().ToString();            string fullDir = "/uploadimage/" + filecutname + ".jpg";            map.Save(context.Request.MapPath(fullDir), System.Drawing.Imaging.ImageFormat.Jpeg);            context.Response.Write(fullDir);        }        #endregion        #region 上传图片        private void fileuploadimage(HttpContext context)        {            HttpPostedFile file = context.Request.Files[0];            string filename = Path.GetFileName(file.FileName);            string filejpg = Path.GetExtension(filename);            string guid = Guid.NewGuid().ToString();            string Dir = "/uploadimage/" + filename + guid + filejpg;            file.SaveAs(context.Request.MapPath(Dir));            context.Response.Write(Dir);        }        #endregion        public bool IsReusable        {            get            {                return false;            }        }    }}

                   
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表