自己定义头像处理,轻巧有用,非常多强大的小技巧在里面哦,快来赞美我一下吧^_^...

        本篇介绍的方法代码。都是摘出来的要点。其它的东西大家须要的话。自己补全吧。



注意以下页面代码里,每个凝视差点儿都是讲的一个有用而又强大有趣的技巧哦!!

因为编写在线编辑器的原因。这个控件也又一次封装了一下,为了參照,原先的代码也不删除了。新封装的就贴在后面吧。

/*
 * 用到的几个样式
 */
<style>
    /* 全兼容的图像自己主动垂直居中的关键样式哦^_^   */
    .imgmid {
        display: inline-block;
        *display: inline;
        *zoom: 1;
        height: 100%;
        width: 1px;
        margin-left: -1px;
        vertical-align: middle;
    }
    /* 图片等比自适应大小的css实现,仅仅要设定最大宽度最大高度就能够了。比用JS实现来的方便轻巧高效多了吧^_^  */
    .autoSize {
        max-width: 360px;
        max-height: 240px;
        vertical-align: middle;
    }
    .activeImg {
        position: absolute;
    }
	/* 方块状的容器,仅仅显示圆形区域的样式哦^_^   */
    .showImg {
        width: 100px;   
        height: 100px;
        display: none;
        position: relative;
        overflow: hidden;
        float: left;
        border-radius: 50%;
        behavior: url(css/PIE.htc);
        float:left;
        clear:right;
    }
</style>
<form method="post" id="fmPhoto" target="hidFrame" enctype="multipart/form-data" action="ReciveUpload">
    <div class="fmc">
	    /* 无刷新表单提交的关键——隐藏的iframe,表单的target指向这个隐藏的iframe */
        <iframe id="hidFrame" name="hidFrame" style="display:none"></iframe>
        <div style="width: 360px; height: 240px; position: relative; float:left;">
            <div style="width: 360px; height: 240px; position: relative; overflow: hidden; float: left; text-align:center;">
                <img alt="图片格式为jpg,最大为2M" id="imgPhoto" src="@srcPhoto" class="autoSize" /><span class="imgmid"></span>/*这个span就是图片垂直居中的关键*/
            </div>
            <img alt="" id="imgScroll" src="~/Images/img_scroll.png" style="z-index: 100; left: 0; top: 0; position: absolute;" />
        </div>
        <div class="showImg">
            <img alt="" id="imgShow" src="@srcPhoto" style="position: absolute;" />
        </div>
        <div style="color:Gray;clear:left; margin-bottom:20px;">图片格式为jpg,图片最大为2M</div>
		/* 能够自己定义样式的file控件。就是这么简单。自己定义一个div,然后里面放一个占满大小的全透明file标签。怎么样,崇拜我吧^_^ */
        <div style ="border:1px solid gray;position:relative; width:100px; height:40px;line-height:40px; text-align:center; vertical-align:middle;font-size:18px;">请选择图像
            <input type="file" id="fileUpload" name="ImageFile" style="position: absolute; width: 100%; height: 100%; filter: alpha(opacity=0); opacity: 0; top: 0; left: 0;" />
        </div>
        <input type="hidden" id="ImgWidth" name="ImgWidth" />
        <input type="hidden" id="ImgHeight" name="ImgHeight" />
        <input type="hidden" id="ImgTop" name="ImgTop" />
        <input type="hidden" id="ImgLeft" name="ImgLeft" />
    </div>    
    <div class="mb">
        <input type="submit" class="lang-btn" id="btnSubmit" value="确定" />
        <a href="javascript:;" class="lang-btn lang-btn-huge lang-cancel mlw">取消</a>
    </div>
</form>
<script type="text/javascript">
    //自己定义光标
    //document.body.style.cursor = "url('http://bbb.com/images/cur.cur')";
    function UploadCallBack(msg) {
        if (msg.indexOf("上传图片出错") == -1) {
		    // 图片样式清理(防止新载入的图片受影响),再加上必须的样式
            $("#imgPhoto").removeAttr("width").removeAttr("height").removeAttr("style").removeClass("activeImg").addClass("autoSize").attr("src", msg);
            $("#imgShow").attr("src", msg);
        } else {
            alert("系统忙,请稍后再试!

"); } } // 图片缩放和移动的代码,也是超简单吧, // 相比网上那些封装好的代码控件。动不动就是几本JS,复杂得要死,又难以维护。 // 我这个实现。算是一个贡献吧,还有助于刚開始学习的人学习和开启智慧^_^ $(function () { var img = $("#imgScroll"); var obj = $("#imgPhoto"); var isMove = false; var x = y = 0; img.on("click", function (event) { if (isMove) { isMove = false; obj.css("cursor", "default"); $(".showImg").hide(); } else { isMove = true; img.css("cursor", "move"); obj.attr("width", obj.width()).attr("height", obj.height()).removeClass("autoSize").addClass("activeImg").css({ top: obj.css("top"), left: obj.css("left") }); var left = obj.css("left") == "auto" ?

0 : obj.css("left"); var top = obj.css("top") == "auto" ?

0 : obj.css("top"); x = event.pageX - parseInt(left); y = event.pageY - parseInt(top); $("#imgShow").attr("width", obj.width()).attr("height", obj.height()).css({ top: obj.css("top") - 70, left: obj.css("left") - 130 }); $(".showImg").show(); } }).on("mouseout", function () { isMove = false; obj.css("cursor", "default"); $(".showImg").hide(); }).on("mousewheel", function (event) { var wm = event.originalEvent.wheelDelta > 0 ? 1 : -1; var width = obj.width() * (10 + wm) / 10;//可适合改动 var height = obj.height() * (10 + wm) / 10; if (width > 100 && height > 100) { obj.width(width).css({ "left": (180 - (width / 2)) }); obj.height(height).css({ "top": (120 - (height / 2)) }); $("#imgShow").width(width).height(height).css({ top: 50 - (height / 2), left: 50 - (width / 2) }); $(".showImg").show(); } }); $(document).mousemove(function (e) { if (isMove) { obj.css({ top: e.pageY - y, left: e.pageX - x }); $("#imgShow").css({ top: e.pageY - y - 70, left: e.pageX - x - 130 }); } }); // file控件响应事件 $("#fileUpload").change(function () { var tmp = this.value.split('\\'); var fileName = tmp[tmp.length - 1].split('.'); document.forms["fmPhoto"].submit(); }); // 表单验证和ajax提交, var valid = $("#fmPhoto").validate({ submitHandler: function () { $("#ImgWidth").val(obj.width()); $("#ImgHeight").val(obj.height()); $("#ImgTop").val(70 - parseInt(obj.css("top"), 10)); $("#ImgLeft").val(130 - parseInt(obj.css("left"), 10)); $.ajax({ url: "http://localhost:22397/Home/Photo", cache: false, type: "post", data: $("#fmPhoto").serialize(), success: function (result) { if (!result) { var errormap = { SystemMsg: "系统忙,请稍后再试。" }; valid.showErrors(errormap, valid.errorlist); } else { if (result.Msg) { valid.showErrors(result.Msg.Map, valid.errorlist); } else { $("#imgUserPhoto").attr("src", result.VirtualPath + result.Name); } } } }); }, rules: { Name: { required: true, } } }); }); </script>


又一次封装的js代码:

    $(function () {
        window.Photo || (window.Photo = {
            x: 0,
            y: 0,
            w: 0,
            h: 0,
            l: 0,
            t: 0,
            mousedown: 0,
            html: '<form method="post" id="PhotoForm" target="hidFrame" enctype="multipart/form-data" action="{action}" style="width:600px;margin:0px auto;position:relative;">'
+ '<iframe id="hidFrame" name="hidFrame" style="display:none"></iframe>'
+ '    <div style="width: 480px; height: 360px; position: relative; float: left; overflow: hidden;">'
+ '        <img id="imgPhoto" src="{img}" οnerrοr="this.src =\'../../Images/Account/DefaultPhoto.png\'" style="position:relative;" />'
+ '        <div id="cover" style="width: 800px;height: 800px;z-index: 100;position: absolute;border: 350px solid rgba(48, 168, 48, 0.5);border-bottom-left-radius: 50%;border-bottom-right-radius: 50%;border-top-left-radius: 50%;border-top-right-radius: 50%;top: -220px;left: -160px;"></div>'
+ '    </div>'
+ '    <div id="showImage" style="width: 100px;height: 100px;display: none;position: relative;overflow: hidden;float: left;border-radius: 50%;">'
+ '        <img alt="" id="imgShow" src="{img}" οnerrοr="this.src=\'../../Images/Account/DefaultPhoto.png\'" style="position: relative;" />'
+ '    </div>'
+ '    <div style="color:Gray;clear:left; margin-bottom:20px;">图片格式为jpg。图片最大为2M</div>'
+ '    <div style="border:1px solid gray;position:relative; width:100px; height:40px;line-height:40px; text-align:center; vertical-align:middle;font-size:18px;display:inline-block;">'
+ '        请选择图像'
+ '        <input type="file" id="fileUpload" name="ImageFile" style="position: absolute; width: 100%; height: 100%; filter: alpha(opacity=0); opacity: 0; top: 0; left: 0;" />'
+ '    </div>'
+ '    <a href="#" style="width:60px;height:30px; margin:10px 0 0 238px;">Cancel</a>'
+ '    <input type="button" style="width:60px;height:30px; margin:10px 0 0 30px;" id="btnSubmit" value="Save" />'
+ '    <input type="hidden" id="CallBcakFunction" name="CallBcakFunction" value="window.parent.Photo.UploadCallBack" />'
+ '    <input type="hidden" id="ImgWidth"  name="width"  />'
+ '    <input type="hidden" id="ImgHeight" name="height" />'
+ '    <input type="hidden" id="ImgTop"    name="top"    />'
+ '    <input type="hidden" id="ImgLeft"   name="left"   />'
+ '</form>',
            UploadCallBack: function (msg) {
                if (msg.indexOf("上传图片出错") != -1) {
                    alert("系统忙,请稍后再试!");
                } else {
                    Photo.image.attr('src', msg);
                }
            },
            show: function (containner,action,saveurl,img) {
                Photo.Content = Photo.Content ? Photo.Content : $(Photo.html.replace('{action}', action).replace('{img}', img)).appendTo($(containner));
                Photo.view = $("#imgShow"),
                Photo.image = $("#imgPhoto"),
                Photo.cover = $("#cover"),
                Photo.watch = $("#showImage");
                $("#fileUpload").change(function () {
                    var tmp = this.value.split('\\');
                    var fileName = tmp[tmp.length - 1].split('.');
                    Photo.Content.submit();
                });
                $("#btnSubmit").on('click', function () {
                    $("#ImgTop").val(parseInt(130 - Photo.t, 10));
                    $("#ImgLeft").val(parseInt(190 - Photo.l, 10));
                    $("#ImgWidth").val(parseInt(Photo.w, 10));
                    $("#ImgHeight").val(parseInt(Photo.h, 10));
                    $.ajax({
                        url: saveurl,
                        cache: false,
                        type: "post",
                        data: $("#PhotoForm").serialize(),
                        success: function (result) {
                            if (!result) {
                                var errormap = { SystemMsg: "系统忙,请稍后再试。" };
                                valid.showErrors(errormap, valid.errorlist);
                            } else {
                                if (result.Msg) {
                                    valid.showErrors(result.Msg.Map, valid.errorlist);
                                } else {
                                    $("#imgUserPhoto").attr("src", result.VirtualPath + result.Name);
                                }
                            }
                        }
                    });
                });
                $(document).mousemove(function (e) {
                    if (Photo.mousedown) {
                        Photo.t += e.pageY - Photo.y;
                        Photo.l += e.pageX - Photo.x;
                        Photo.image.css({ top: Photo.t, left: Photo.l });
                        Photo.view.css({ top: Photo.t - 130, left: Photo.l - 190 });
                        Photo.x = e.pageX;
                        Photo.y = e.pageY;
                    }
                });
                Photo.image.on("load", function (e) {
                    var img = new Image();
                    img.src = this.src;
                    var ow = img.width, oh = img.height,
                    b = 3 * Photo.w > 4 * Photo.h;
                    Photo.w = b ? 480 : (ow * 360 / oh);
                    Photo.h = b ?

(oh * 480 / ow) : 360; Photo.l = (480 - Photo.w) / 2, Photo.t = (360 - Photo.h) / 2; Photo.image.css({ width: Photo.w, height: Photo.h, top: Photo.t, left: Photo.l }); Photo.view.css({ width: Photo.w, height: Photo.h, top: Photo.t - 130, left: Photo.l - 190 }).attr('src', this.src); }); Photo.cover.on("mousedown", function (e) { e.stopPropagation(); Photo.mousedown = true; Photo.cover.css("cursor", "move"); Photo.watch.show(); Photo.x = e.pageX; Photo.y = e.pageY; }).on("mouseup", function (e) { e.stopPropagation(); Photo.mousedown = false; Photo.cover.css("cursor", "default"); Photo.watch.hide(); }).on("mousewheel", function (e) { e.stopPropagation(); var wm = e.originalEvent.wheelDelta > 0 ? 1 : -1; nw = Photo.w * (10 + wm) / 10;//可适当改动 nh = Photo.h * (10 + wm) / 10; if (nw > 100 && nh > 100) { Photo.l = Photo.l + (Photo.w - nw) / 2; Photo.t = Photo.t + (Photo.h - nh) / 2; Photo.w = nw; Photo.h = nh; Photo.image.css({ width: Photo.w, height: Photo.h, top: Photo.t, left: Photo.l }); Photo.view.css({ width: Photo.w, height: Photo.h, top: Photo.t - 130, left: Photo.l - 190 }); } }); } }); Photo.show($('#customPhoto'), 'ReciveUpload', 'http://localhost:7427/Home/Photo', '@Model.xPhoto'); });


后台的相关方法也放这吧,有须要的能够直接拿去用

        public ActionResult Photo()
        {
            var guid = Cookies.ReadCookie("UserGuid");
            var account = DAL.xV_Account.GetAccountByCode(Guid.Parse(guid));
            Session["account"] = account;
            return View(account);
        }
        [HttpPost]
        public JsonResult Photo(int width,int height,int left,int top)
        {
            var account = Session["account"] as DAL.xV_Account;
            var p = Session["tmpImage"] as string;
            if (!string.IsNullOrWhiteSpace(p))
            {
                ImageHelper.CutImage(Image.FromFile(p), width, height, left, top, 100, 100, p, account.xAccountCode);
                account.xPhoto = "http://" + Request.Url.Authority + "/Images/Photos/" + account.xAccountCode + ".jpg";
                DAL.xV_Account.UpdatePhoto(account);
            }
            return Json(account);
        }
        /// <summary>
        /// 接收页面无刷新提交的文档(本例为图片)。并保存在暂时文件夹中,用Session记录文件夹
        /// </summary>
        /// <returns></returns>
        public ActionResult ReciveUpload()
        {
            string result = "<script type='text/javascript'>" + Request["CallBcakFunction"] + "('";
            try
            {
                var account = Session["account"] as DAL.xV_Account;
                var p = Session["tmpImage"] as string;
                string fileName = Request.Files[0].FileName.Substring(Request.Files[0].FileName.LastIndexOf('\\') + 1);
                if (p == null)
                {
                    p = "D:\\WorkSpace\\Project\\Viva\\Viva\\Images\\Photos\\" + account.xAccountCode + ".jpg";
                }
                Session["tmpImage"] = p;
                //保存原图
                ImageHelper.SaveImage(Request.Files[0], p.Substring(0, p.LastIndexOf('\\')), account.xAccountCode + ".jpg", new string[] { "jpg","jpeg" }, 5);
                //返回保存的缩略图的路径
                result += "http://" + Request.Url.Authority + "/Images/Photos/" + account.xAccountCode + ".jpg";
            }
            catch
            {
                result += "上传图片出错!

请稍后再试,或寻求管理员的帮助."; } return Content(result + "');</script>"); } public static bool CutImage(Image image, int sWidth, int sHeight, int left, int top, int width, int height, string path, string name) { //用指定的大小和格式初始化 Bitmap 类的新实例 var bitmap = new Bitmap(sWidth, sHeight, PixelFormat.Format32bppArgb); //从指定的 Image 对象创建新 Graphics 对象 var graphics = Graphics.FromImage(bitmap); //清除整个画图面并以透明背景色填充 graphics.Clear(Color.Transparent); //在指定位置而且按指定大小绘制 原图片 对象 graphics.DrawImage(image, new Rectangle(0, 0, sWidth, sHeight)); graphics.Dispose(); // 目标区域 var destRect = new Rectangle(0, 0, width, height); // 源图区域 var srcRect = new Rectangle(left, top, width, height); // 新建Graphics对象 var newImage = new Bitmap(width, height); var g = Graphics.FromImage(newImage); // 画图平滑程序 g.SmoothingMode = SmoothingMode.HighQuality; // 图片输出质量 g.CompositingQuality = CompositingQuality.HighQuality; // 输出到newImage对象 g.DrawImage(bitmap, destRect, srcRect, GraphicsUnit.Pixel); // 释放画图对象 g.Dispose(); // 保存图像 if (File.Exists(path + name)) { File.Delete(path + name); } newImage.Save(path + name); return true; }


上面有个SaveImage方法, 点此查看


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值