上传头图片带预览剪切NET版-兼容大部分浏览器

1.上传页面WebForm2.aspx.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication2.WebForm2" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="jquery.min.js"></script>
    <script src="ajaxupload.js"></script>
    <script src="jquery.imgareaselect.min.js"></script>
    <script src="jquery.imgareaselect.pack.js"></script>
    <link href="imgareaselect-default.css" rel="stylesheet" />

</head>
<body>
    <form id="form1" runat="server">
        <input id="med" type="text" />
        上传图片:<input type="text" id="txtFileName" /><div id="btnUp" style="width: 300px;" class="btnsubmit">浏览</div>
         <div style=" width:200px; height:300px; float: left;">
              <input type="button" id="btnCut" value="进行裁剪" />
           
        <img id="picTest"  alt="鼠标选中图表某个区域进行裁剪" title="鼠标选中图表某个区域进行裁剪" /></div>
   
        <!--用于显示裁剪后的图片-->
        <div id="divNewPic" style="margin-left:500px">
            <img id="showPicture" />
        </div>
    </form>
    <script type="text/javascript">
        //定义几个全局变量用于记录图片选择区域的左上角角和右下角两个点的x和y坐标
        var x1 = 0, y1 = 0, x2 = 0, y2 = 0;
        $(document).ready(function () {
            //页面初始化时监听某个图片对象的鼠标区域选择事件
            $(‘#picTest‘).imgAreaSelect({
                onSelectEnd: function (img, selection) {
                    x1 = selection.x1;
                    y1 = selection.y1;
                    x2 = selection.x2;
                    y2 = selection.y2;
                }
            });
            //给页面button按钮绑定事件
            $("#btnCut").click(function () {
                $("#showPicture").remove();
                $("#divNewPic").hide();
                ImgAreaSelectCut();
                //$("<img />").remove($(‘#divNewPic‘));
            });
            var button = $(‘#btnUp‘), interval;
            new AjaxUpload(button, {
                action: ‘Handler.ashx‘,
                name: ‘myfile‘,
                onSubmit: function (file, ext) {
                    if (!(ext && /^(jpg|jpeg|JPG|JPEG)$/.test(ext))) {
                        alert(‘图片格式不正确,请选择 jpg 格式的文件!‘, ‘系统提示‘);
                        if (navigator.userAgent.indexOf("MSIE") > 0) {
                            $("#med").attr("value", "");
                        }                                         
                            $("#med").val(‘‘);
                            $("#picTest").attr("src", "");
                        return false;
                    }
                },
                onComplete: function (file, response) {
                    //file 本地文件名称,response 服务器端传回的信息
                    var k = response.replace("<pre>", "").replace("</pre>", "");
                    if (k == ‘-1‘) {
                        alert(‘您上传的文件太大啦!请不要超过150K‘);
                        $("#picTest").attr("src", "");
                        $("#med").val(‘‘);
                        if (navigator.userAgent.indexOf("MSIE") > 0) {
                            $("#med").attr("value", "");
                        }
                    }
                    else {
                        $("#med").val(k);
                        $("#picTest").attr("src", k);
                    }
                }
            });
        });

        //通过Ajax异步提交相关裁剪数据至后台服务 接收裁剪后的图片地址并将其显示在页面某个div容器内
        function ImgAreaSelectCut() {
           
            $.ajax({
                url: "ImageSelectCutService.aspx?dateTime=" + new Date().toString(),
                dataType: "json", //返回数据格式为json
                async: false, //异步提交数据
                data: "&x1=" + x1 + "&y1=" + y1 + "&x2=" + x2 + "&y2=" + y2+"&filename="+document.getElementById("med").value,
                success: function (data) {
                    if (data) {
                        if (data.state = 0) {
                            alert(data.msg);
                        } else {
                            $("#divNewPic").show();
                            var newPicPath = data.msg;
                            if (navigator.userAgent.indexOf("MSIE") > 0)
                            {
                                document.getElementById("showPicture").src = newPicPath;
                            }
                            //document.getElementById("showPicture").setAttribute("src", "");
                            //document.getElementById("showPicture").setAttribute("src", newPicPath);
                            $("#divNewPic").html("<img id=‘showPicture‘ src=‘" + newPicPath + "‘/>");
                          //  $("<img id=‘showPicture‘ />").appendTo($(‘#divNewPic‘)).attr("src", newPicPath);
                            $("#showPicture").attr("src", "");
                            $("#showPicture").attr("src", newPicPath);
                        }
                    }
                },
                error: function (msg) {
                    alert(msg);
                }
            });
        }
    </script>
</body>
</html>
2,上传处理页面Handler.ashx

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

namespace WebApplication2
{
    /// <summary>
    /// Handler 的摘要说明
    /// </summary>
    public class Handler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";

            string url = context.Request["med"];

            HttpPostedFile postedFile = context.Request.Files[0];
            string savePath = "/images/";
            int filelength = postedFile.ContentLength;
            string filename = postedFile.FileName;
            int fileSize = 163600; //150K
            string fileName = ""; //返回的上传后的文件名
            if (filelength <= fileSize)
            {

                byte[] buffer = new byte[filelength];

                postedFile.InputStream.Read(buffer, 0, filelength);

                fileName = UploadImage(buffer, savePath, "jpg", url);
                //fileName = UploadImage(buffer, savePath, filename, url);
            }
            else
            {
                fileName = "-1";
            }
            //fileName = fileName +","+ url;
            context.Response.Write(fileName);
        }

        public static string UploadImage(byte[] imgBuffer, string uploadpath, string ext, string url)
        {
            try
            {
                System.IO.MemoryStream m = new MemoryStream(imgBuffer);

                if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadpath)))
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadpath));

                if (File.Exists(url))
                {
                    //如果存在则删除
                    File.Delete(url);
                }

                string imgname = CreateIDCode() + "." + ext;

                string _path = HttpContext.Current.Server.MapPath(uploadpath) + imgname;

                Image img = Image.FromStream(m);
                img.Save(_path);
                if (ext == "jpg")
                    img.Save(_path, System.Drawing.Imaging.ImageFormat.Jpeg);
                else
                    img.Save(_path, System.Drawing.Imaging.ImageFormat.Gif);
                m.Close();

                return uploadpath + imgname;
                //  return _path;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        public static string CreateIDCode()
        {
            DateTime Time1 = DateTime.Now.ToUniversalTime();
            DateTime Time2 = Convert.ToDateTime("1970-01-01");
            TimeSpan span = Time1 - Time2;   //span就是两个日期之间的差额   
            string t = span.TotalMilliseconds.ToString("0");

            return t;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

3,在线切割生成缩略图页面ImageSelectCutService.aspx

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class ImageSelectCutService : System.Web.UI.Page
    {
      
        #region 参数定义
        /// <summary>
        /// 两个坐标点的x和y坐标值
        /// </summary>
        public int x1, y1, x2, y2;
     
        public string picPath = "";
        public string newPicPath = "/images/new/new.jpg";
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            #region 获取参数
            picPath = Request.QueryString["filename"];
            string[] temp = picPath.Split(‘/‘);
            newPicPath = "/images/new/" + temp[2];
            x1 = string.IsNullOrEmpty(Request["x1"]) ? 0 : Convert.ToInt32(Request["x1"]);
            y1 = string.IsNullOrEmpty(Request["y1"]) ? 0 : Convert.ToInt32(Request["y1"]);
            x2 = string.IsNullOrEmpty(Request["x2"]) ? 0 : Convert.ToInt32(Request["x2"]);
            y2 = string.IsNullOrEmpty(Request["y2"]) ? 0 : Convert.ToInt32(Request["y2"]);

            ///裁剪图片
            CutImage(picPath, newPicPath, x1, y1, x2, y2);
            #endregion
        }

        private void CutImage(string picPath, string newPicPath, int x1, int y1, int x2, int y2)
        {
            string returnJson = "";
            //获取所选区域的高宽值
            int width = x2 - x1;
            int height = y2 - y1;
            try
            {
                ///将图片文件字节化
                Bitmap bm = new Bitmap(Server.MapPath(picPath));
                //处理JPG质量的函数
                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo ici = null;
                foreach (ImageCodecInfo codec in codecs)
                {
                    if (codec.MimeType == "image/jpeg")
                    {
                        ici = codec;
                        break;
                    }
                }
                int level = 100; //图片质量

                EncoderParameters ep = new EncoderParameters();
                ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)level);

                // 裁剪图片
                Rectangle cloneRect = new Rectangle(x1, y1, width, height);
                PixelFormat format = bm.PixelFormat;
                Bitmap cloneBitmap = bm.Clone(cloneRect, format);
                //保存图片
                cloneBitmap.Save(Server.MapPath(newPicPath), ici, ep);
                cloneBitmap.Dispose();
                bm.Dispose();
                returnJson = "{\"state\":\"0\",\"msg\":\"" + newPicPath + "\"}";
            }
            catch (Exception e)
            {
                returnJson = "{\"state\":\"1\",\"msg\":\"" + e.Message + "\"}";
            }
            Response.Write(returnJson);
            Response.End();
        }
    }
}

4,引用CSS样式imgareaselect-default.css

/*
 * imgAreaSelect default style
 */

.imgareaselect-border1 {
 background: url(border-v.gif) repeat-y left top;
}

.imgareaselect-border2 {
    background: url(border-h.gif) repeat-x left top;
}

.imgareaselect-border3 {
    background: url(border-v.gif) repeat-y right top;
}

.imgareaselect-border4 {
    background: url(border-h.gif) repeat-x left bottom;
}

.imgareaselect-border1, .imgareaselect-border2,
.imgareaselect-border3, .imgareaselect-border4 {
    filter: alpha(opacity=50);
 opacity: 0.5;
}

.imgareaselect-handle {
    background-color: #fff;
    border: solid 1px #000;
    filter: alpha(opacity=50);
    opacity: 0.5;
}

.imgareaselect-outer {
    background-color: #000;
    filter: alpha(opacity=50);
    opacity: 0.5;
}

.imgareaselect-selection { 
}

5,引用JS

技术分享

 图片显示根据个人需要,有什么问题可以留言

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。