学习篇:截取头像上传和Jquery ui

上一篇写了用swfupload组件,实现无刷新的上传图片。

今天,再加一个功能,就是截取图片的部分。

1.首先,将上传的图片作为背景图片来展示在一个div标签中。

//这里放了一个全局的变量,因为下面还要用到它
var
imgPath; function backgroundImg(file, serverData) { imgPath = serverData.split(":"); if (imgPath[0] == "ok") { var width = imgPath[2]; var height = imgPath[3]; $("#containerDiv").css("backgroundImage", "url(" + imgPath[1] + ")").css("width", width + "px").css("height", height + "px"); } }

2.再背景图片上,展示一个小点的div,这个div可以调整大小,可以拖动。这里就需要用到Jquery ui 了。两个方法:resizable(),draggable();

  $(function () {
            $("#cut_div").resizable({
                containment: 'parent', aspectRatio: 1 / 1
            }).draggable({
                containment: 'parent'
            });
//下面的点击事件写在这里--
};

3.点击button的时候,执行js代码,用offset()获取绝对坐标,获取top,left,width,height,imgSrc 传到后台截取后,将图片地址返回。

 $("#btnCut").click(function () {
                alert("1");
                var relTop = $("#cut_div").offset().top - $("#containerDiv").offset().top;
                var relLeft = $("#cut_div").offset().left - $("#containerDiv").offset().left;
                var width = $("#cut_div").width();
                var height = $("#cut_div").height();
                $.post("../ashx/Cutupload.ashx", { "action": "cut", "top": relTop, "left": relLeft, "width": width, "height": height, "imgSrc": imgPath[1] }, function (data) {
                    alert("2");
                    $("#background").attr("src", data);
                }, "text");
            });

4.当然,要有前面代码中出现的这个一般处理程序。

处理截图工作的一般处理程序
 public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string action = context.Request.Params["action"];
            if (action == "up")
            {
                HttpPostedFile file = context.Request.Files["Filedata"];
                string fileName = Path.GetFileName(file.FileName);
                string fileExtention = Path.GetExtension(file.FileName);

                if (fileExtention == ".jpg")
                {
                    string savePath = "/FileUpload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
                    //************************
                    Directory.CreateDirectory(Path.GetDirectoryName(context.Server.MapPath(savePath)));

                    string fullPath = savePath + Common.Common.GetStreamMD5(file.InputStream) + fileExtention;
                    file.SaveAs(context.Server.MapPath(fullPath));

                    using (Image img = Image.FromStream(file.InputStream))
                    {
                        context.Response.Write("ok:" + fullPath + ":" + img.Width + ":" + img.Height);
                    }
                }
                else
                {
                    throw new Exception("文件类型有错~!");
                }
            }
            else if (action == "cut")
            {
              

                string top = context.Request.Form["top"];
                string left = context.Request.Form["left"];
                string width = context.Request.Form["width"];
                string height = context.Request.Form["height"];
                string imgSrc = context.Request.Form["imgSrc"];

                using (Image img = Image.FromFile(context.Request.MapPath(imgSrc)))
                {
                    Bitmap map = CutBitmap(img, Convert.ToInt32(width), Convert.ToInt32(height), Convert.ToInt32(left), Convert.ToInt32(top));
                    string savePath = "/FileUpload/Cut/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
                    //************************
                    Directory.CreateDirectory(Path.GetDirectoryName(context.Server.MapPath(savePath)));
                    string newFile = Guid.NewGuid().ToString().Substring(0, 8);
                    string fullPath = savePath + newFile + ".jpg";
                    map.Save(context.Request.MapPath(fullPath));
                    context.Response.Write(fullPath);
                }

            }


        }
        //截图方法
        private static Bitmap CutBitmap(Image oldImage, int width, int height, int x, int y)
        {
            if (oldImage == null)
                throw new ArgumentNullException("oldImage");

            Bitmap newBitmap = new Bitmap(width, height);
            using (Graphics g = Graphics.FromImage(newBitmap))
            {
                g.InterpolationMode = InterpolationMode.High;
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.DrawImage(oldImage, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
                g.Save();
            }
            return newBitmap;
        }

5.div布局也上传一下吧,呵呵~~~

 <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>
        <div id="containerDiv" style="width: 300px; height: 300px">
            <div id="cut_div" style="border: 1px solid red; width: 100px; height: 100px">
            </div>
        </div>
        <img id="background" alt="头像" />
        <input type="button" id="btnCut" value="截取"/>
    </div>

OK了,大功告成, 这就能完成 截取头像并上传的功能了。

posted @ 2012-10-22 23:54  2月18号  阅读(1670)  评论(0编辑  收藏  举报