基于swuplaod图片的上传截取

来源:互联网 发布:一加性能怪兽 知乎 编辑:程序博客网 时间:2024/04/28 03:59

前台代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>    <link href="../Css/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />    <script src="../SWFUpload/swfupload.js" type="text/javascript"></script>    <script src="../SWFUpload/handlers.js" type="text/javascript"></script>    <script src="../js/jquery-1.7.1.js" type="text/javascript"></script>    <script src="../js/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script>    <script type="text/javascript">        var swfu;        window.onload = function() {            swfu = new SWFUpload({                // Backend Settings                upload_url: "/ashx/cutPhoto.ashx?action=up",                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: ShowData,                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            });        };        //上传成功以后        var d;//保存了上传成功图片的路径信息        function ShowData(file, serverData) {             d = serverData.split(":");            if (d[0] === "ok") {                             // $("#imgSrc").attr("src", d[1]);                $("#divContent").css("backgroundImage", "url(" + d[1] + ")").css("width", d[2] + "px").css("height", d[3] + "px");            }        }        $(function() {            $("#divCut")                .draggable({ containment: 'parent' })                .resizable({                    containment: '#divContent'                });            //开始获取要截取头像的范围            $("#btnCut")                .click(function() {                    //offset():获取元素绝对坐标 top距浏览器顶端的距离                    var y = $("#divCut").offset().top - $("#divContent").offset().top; //纵坐标                    var x = $("#divCut").offset().left - $("#divContent").offset().left; //横坐标.                    var width = $("#divCut").width(); //宽度                    var height = $("#divCut").height(); //高度                    //将截取图片的访问通过AJAX发送到服务端.                    $.post("/ashx/cutPhoto.ashx",                        {                            "action": "cut",                            "x": parseInt(x),                            "y": parseInt(y),                            "width": parseInt(width),                            "height": parseInt(height),                            "imgSrc": d[1]                        },                        function(data) {                            $("#imgSrc").attr("src", data);                        });                });        });</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="divContent" style="width:300px; height:300px">                <div id="divCut" style="width:100px; height:100px; border:solid 1px red">                                    </div>             </div>    </div>       <input type="button" value="截取头像" id="btnCut" />       <img id="imgSrc" /></div>    </form></body></html>

后台代码
        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            string action = context.Request["action"];            if (action == "up")//表示上传            {                HttpPostedFile file = context.Request.Files["Filedata"];//接收文件.                string fileName = Path.GetFileName(file.FileName);//获取文件名。                string fileExt = Path.GetExtension(fileName);//获取文件类型.                if (fileExt == ".jpg")                {                    using (Image img = Image.FromStream(file.InputStream))//根据上传的文件创建一个Image.                    {                        file.SaveAs(context.Server.MapPath("/UploadImage/" + fileName));                        context.Response.Write("ok:/UploadImage/" + fileName + ":" + img.Width + ":" + img.Height);                    }                }            }            else if (action == "cut")//头像截取            {                int x = Convert.ToInt32(context.Request.Form["x"]);                int y = Convert.ToInt32(context.Request.Form["y"]);                int width = Convert.ToInt32(context.Request.Form["width"]);                int height = Convert.ToInt32(context.Request.Form["height"]);                string imgSrc = context.Request.Form["imgSrc"];//获取上传成功的图片路径                //根据传递过来的范围,将该范围的图片画到画布上,将画布保存。                using (Bitmap map = new Bitmap(width, height))                {                    using (Graphics g = Graphics.FromImage(map))//为画布创建画笔.                    {                        using (Image img = Image.FromFile(context.Server.MapPath(imgSrc)))//创建img                        {                            //将图片画到画布上                            //第一:对哪张图片进行操作                            //二:画多么大                            //三:画哪部分                            g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);                            string newfile = Guid.NewGuid().ToString();                            map.Save(context.Server.MapPath("/UploadImage/" + newfile + ".jpg"));//将画布上的图片按照GUID命名保存                            context.Response.Write("/UploadImage/" + newfile + ".jpg");                        }                    }                }            }        }        public bool IsReusable        {            get            {                return false;            }        }

0 0
原创粉丝点击