ASP.NET图片上传和截取

码农公社  210.net.cn   210= 1024  10月24日一个重要的节日--码农(程序员)节

图片的上传直接使用ajax就可以了,截取图片的话使用到Jcrop插件。截取图片插件:http://code.ciaoca.com/jquery/jcrop/


前端

添加引用

<script src="../js/jquery.min.js"></script>
<link href="../Css/jquery.Jcrop.min.css" rel="stylesheet" />
<script src="../js/jquery.Jcrop.min.js"></script>


HTML代码

<input type="file" name="photo" id="photo" value="" placeholder="免冠照片">
<input type="button" onclick="postData();" value="下一步" name="" style="width: 100px; height: 30px;">
<img id="showPhoto" />

JavaScript代码


<script type="text/javascript">
        //文件上传方法
        function postData() {
            var formData = new FormData();
            //上传文件的变量名
            formData.append("Filedata", $("#photo")[0].files[0]);
            $.ajax({
                url: "/ashx/upload.ashx?action=upload", /*接口域名地址*/
                type: 'post',
                data: formData,
                contentType: false,
                processData: false,
                success: function (res) {
                    $("#showPhoto").attr("src", res);
                    CutPhoto();
                }
            })
        }
        //截图
        function CutPhoto() {
            var jcropApi;
            $('#showPhoto').Jcrop({
                //选框选定时的事件
                onSelect: function (c) {
                    $.ajax({
                        url: "/ashx/upload.ashx?action=cut",
                        type: "post",
                        data: {
                            "x": c.x,
                            "y": c.y,
                            "width": c.w,
                            "height": c.h,
                            "imgSrc": $("#showPhoto").attr("src")
                        },
                        success: function () {

                        }
                    });
                },
                allowSelect: true,//允许新选框
                baseClass: 'jcrop'
            }, function () {
                jcropApi = this;
            });
        }
    </script>


后台 

添加一个一般处理程序upload.ashx 

代码


public class upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //判断action
            string action = context.Request["action"];
            if (action == "upload")
            {
                Upload(context);
            }
            else if (action == "cut")
            {
                CutPhoto(context);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        private void Upload(HttpContext context)
        {
            //获取文件
            HttpPostedFile file = context.Request.Files["Filedata"];
            //判断文件是否为空
            if (file != null)
            {
                //获取文件名
                string fileName = Path.GetFileName(file.FileName);
                //获取文件扩展名
                string fileExt = Path.GetExtension(fileName);
                //判断文件扩展名是否正确
                if (fileExt == ".jpg")
                {
                    //获得文件路径
                    string filePath = "/UploadFile/" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day;
                    //判断文件是否存在
                    if (!System.IO.Directory.Exists(context.Request.MapPath(filePath)))
                    {
                        //不存在则创建
                        Directory.CreateDirectory(context.Request.MapPath(filePath));
                    }
                    //生成新的文件名
                    string newFileName = filePath + "/" + Guid.NewGuid() + fileExt;
                    //保存文件
                    file.SaveAs(context.Request.MapPath(newFileName));
                    //返回文件路径
                    context.Response.Write(newFileName);
                }
            }
        }
        /// <summary>
        /// 截取图片
        /// </summary>
        /// <param name="context"></param>
        private void CutPhoto(HttpContext context)
        {
            int x = Convert.ToInt32(context.Request["x"]);
            int y = Convert.ToInt32(context.Request["x"]);
            int width = Convert.ToInt32(context.Request["width"]);
            int height = Convert.ToInt32(context.Request["height"]);
            string imgSrc = context.Request["imgSrc"];
            //创建画布
            using (Bitmap bitmap = new Bitmap(width, height))
            {
                //创建画笔
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    //创建图片
                    using (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 newImgName = Guid.NewGuid().ToString()+".jpg";
                        string dir = "/UploadFile/" + newImgName;
                        bitmap.Save(context.Request.MapPath(dir),System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }
            }
        }
    }



转自https://www.cnblogs.com/birdGe/p/11942614.html

评论