头像截取

使用SWFUpload组件实现无刷新上传,配合JQuery UI实现头像截取

SWFUpload配置与使用

//1.1 引入脚本文件
<script src="SWFUpload/swfupload.js" type="text/javascript"></script> //script1
<script src="SWFUpload/handlers.js" type="text/javascript"></script>  //script2
//1.2 SWFUpload配置使用
        var swfu;
        window.onload = function () {
            swfu = new SWFUpload({
                // Backend Settings
                upload_url: "UpLoadPhoto.ashx?action=uploadPhoto",  //
                post_params: {
                    "ASPSESSID": "<%=Session.SessionID %>"
                },

                //上传设置
                file_size_limit: "10 MB",  //限制上传文件大小
                file_types: "*.jpg",       //限制文件格式
                file_types_description: "JPG Images",
                file_upload_limit: 0,      //Zero means unlimited
                file_post_name: "ajaxFile",

                //事件设置
                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: Success,  //上传后执行 将image的相对路径返回
                upload_complete_handler: uploadComplete,

                //上传按钮设置
                button_image_url: "SWFUpload/images/XPButtonNoText_160x22.png",
                button_placeholder_id: "spanButtonPlaceholder",
                button_width: 160,
                button_height: 22,
                button_text: '请上传照片(10 MB Max)',
                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",      // 相对路径
                flash9_url: "../swfupload/swfupload_FP9.swf", // 相对路径

                custom_settings: {
                    //upload_target: "divFileProgressContainer"
                },

                //Debug Settings
                debug: false
            });
        };
        var data;  //保存上传的照片的路径和文件名
        function Success(file, serverData) {
            var filePath = serverData.split("|")[1];
            if (filePath!="undefined"||filePath!="") {
                data = filePath;
                $("#leftContainer").css("backgroundImage", "url(" + filePath + ")");
            } else {
                alert("上传错误!");
            }  
        };
<!-- 2.Aspx上传按钮、截取按钮等 -->
 <div id="Container">
        <div id="topContainer">
            <div id="swfu_container" style="width: 50px; height: 30px;">
                <div>
                    <span id="spanButtonPlaceholder"></span>
                </div>
                <%-- <div id="divFileProgressContainer" style="height: 75px;">
                     返回信息
                     </div>--%>
            </div>
        </div>
        <div id="leftContainer" style="clear: both;">
            <div id="cutDiv" style="border: 1px solid red; width: 100px; height: 100px;">
            </div>
        </div>
        <div id="rigthContainer">
            <div style="width: 100px; height: 100px;">
                <img id="imgok" src="" alt="imgPhoto" />
            </div>
        </div>
        <div id="bottomContainer" style="clear: both;">
            <input type="button" id="btnCut" value="截取" style="margin: 10px auto 0px auto;" />
        </div>
</div>

截取

        
//用JQuery UI resizable(大小)、draggable(拖动) 获取image的坐标
        $(function () {           
            $("#cutDiv").resizable({
                aspectRatio: 1 / 1,
                maxHeight: 180,
                maxWidth: 180,
                minHeight: 48,
                minWidth: 48
            }).draggable({ containment: 'parent' });
            //获取要截取头像的坐标                      
            $("#btnCut").click(function () {
                //获取绝对坐标
                var relTop = $("#cutDiv").offset().top - $("#leftContainer").offset().top;
                var relLeft = $("#cutDiv").offset().left - $("#leftContainer").offset().left;
                var width = $("#cutDiv").width();
                var height = $("#cutDiv").height();
                $.post("AjaxPhoto.ashx", { "action": "cutPhoto", "top": relTop, "left": relLeft, "width": width, "height": height, "imgSrc": data }, function (msg) {
                    $("#imgok").attr("src", msg); //设置img路径。
                }, "text");
            });
        });

后台处理

 public void ProcessRequest(HttpContext context) {
            context.Response.ContentType = "text/plain";
            string action = context.Request["action"];
            if (action == "uploadPhoto") {
                UpLoadPhoto(context);
            }
            else {
                CutPhoto(context);
            }
        }
        /// <summary>
        /// 上传照片并生成缩略图
        /// </summary>
        private void UpLoadPhoto(HttpContext context) {
            HttpPostedFile postedFile = context.Request.Files["ajaxFile"];
            if (postedFile == null) {
                context.Response.Write("File is null");
                context.Response.End();
            }
            string fileExtension = Path.GetExtension(postedFile.FileName);
            string[] containsExtentsion = { ".jpg", ".JPG", "PNG", "png" };
            if (containsExtentsion.Contains(fileExtension)) {
                string guid = Guid.NewGuid().ToString().Substring(0, 8);
                string saveFileName = "Files/" + guid + fileExtension;
                string saveFilePath = context.Server.MapPath(saveFileName);
                postedFile.SaveAs(saveFilePath);
                using (Image image = Image.FromStream(postedFile.InputStream)) {
                    int iWidth = 400;     //生成缩略图的宽度
                    int iHeightt = 400;   //生成缩略图的高度
                    int x = 0;
                    int y = 0;
                    int iOldWidth;        //上传图片的宽度
                    int iOldHeight;       //上传图片的高度
                    if (image.Width / (double)image.Height > iWidth / (double)iHeightt) {
                        iOldHeight = image.Height;
                        iOldWidth = image.Height * iWidth / iHeightt;
                        y = 0;
                        x = (image.Width - iOldWidth) / 2;
                    }
                    else {
                        iOldWidth = image.Width;
                        iOldHeight = image.Width * 400 / iWidth;
                        x = 0;
                        y = (image.Height - iOldHeight) / 2;
                    }
                    using (Image bitmap = new Bitmap(iWidth, iHeightt)) {
                        using (Graphics graphics = Graphics.FromImage(bitmap)) {
                            graphics.InterpolationMode = InterpolationMode.High;
                            graphics.SmoothingMode = SmoothingMode.HighQuality;
                            graphics.Clear(Color.Transparent);
                            graphics.DrawImage(image, new Rectangle(0, 0, iWidth, iHeightt),
                              new Rectangle(x, y, iOldWidth, iOldHeight), GraphicsUnit.Pixel);
                            bitmap.Save(saveFilePath);
                            context.Response.Write("ok|" + saveFileName);
                        }
                    }
                }
            }
            else {
                context.Response.Write("error");
            }
            context.Response.End();
        }

        ///<summary>
        ///根据坐标生成头像
        ///</summary>
        private void CutPhoto(HttpContext context) {
            int iTop = context.Request["top"] == null ? 0 : int.Parse(context.Request["top"]);
            int iLeft = context.Request["left"] == null ? 0 : int.Parse(context.Request["left"]);
            int iWidth = context.Request["width"] == null ? 100 : int.Parse(context.Request["width"]);
            int iHeight = context.Request["height"] == null ? 100 : int.Parse(context.Request["height"]);
            string sImgSrc = context.Request["imgSrc"];
            if (sImgSrc == null) {
                context.Response.Write("File Path is null");
                context.Response.End();
            }
            using (Image image = Image.FromFile(context.Server.MapPath(sImgSrc))) {
                string guid = Guid.NewGuid().ToString().Substring(0, 8);
                string saveFile = "Files/" + guid + ".jpg";
                string saveFilePath = context.Server.MapPath(saveFile);
                using (Bitmap bitmap = new Bitmap(iWidth, iHeight)) {
                    using (Graphics graphics = Graphics.FromImage(bitmap)) {
                        graphics.InterpolationMode = InterpolationMode.High;
                        graphics.SmoothingMode = SmoothingMode.HighQuality;
                        graphics.DrawImage(image, new Rectangle(0, 0, iWidth, iHeight),
                          new Rectangle(iLeft, iTop, iWidth, iHeight), GraphicsUnit.Pixel);
                        bitmap.Save(saveFilePath);
                        context.Response.Write(saveFile);
                        context.Response.End();
                    }
                }
            }
        }

在上传照片或图片的时候,如果照片太大,会报错的,解决方法在webconfig文件中找到<system.web>节点,在该节点下加入<httpRuntime maxRequestLength="900000" executionTimeout="200"/> <!--设置最大的请求报文的长度与设置请求的允许执行时间-->

posted @ 2013-09-17 17:56  秋壶冰月  阅读(3793)  评论(1编辑  收藏  举报