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

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



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

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

/*
 * 用到的几个样式
 */
<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}" onerror="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}" onerror="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方法,点此查看








本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5250024.html,如需转载请自行联系原作者

相关文章
|
4月前
|
C# 数据库
C#桌面文案小工具 ,详细带解说图(带源码)
C#桌面文案小工具 ,详细带解说图(带源码)
|
6月前
|
存储 数据可视化 JavaScript
Three.js:打造独一无二的3D模型可视化编辑神器!
因为之前工作过的可视化大屏项目开发3d大屏组件模块需要用到Three.js来完成,其主功能是实现对3d模型的材质,灯光,背景,动画。等属性进行可视化的编辑操作以及模型编辑数据的存储和模型在大屏上面的拖拽显示
221 1
Three.js:打造独一无二的3D模型可视化编辑神器!
|
8月前
|
自然语言处理 Python Windows
|
11月前
|
存储 Serverless
微信小游戏制作工具中的函数应该如何使用
在微信小游戏制作工具中是没有私有函数这个概念的,也就是说所有的函数都是公共的,大家都可以使用,而且函数也没有返回值的概念,想拿到函数运行的结果只能通过设置一个全局变量,将结果存储在全局变量中,然后通过这个全局变量来使用。这种方法有很多的弊端,尤其是在有大量的克隆体存在时,每个克隆体都使用同一个函数,都去设置同一个全局变量,就会造成意想不到的结果。
213 0
|
11月前
从零开始手把手教你使用javascript+canvas开发一个塔防游戏04右侧信息展板
从零开始手把手教你使用javascript+canvas开发一个塔防游戏04右侧信息展板
74 0
|
前端开发 搜索推荐 索引
重学前端 5 # 如何运用语义类标签来呈现Wiki网页?
重学前端 5 # 如何运用语义类标签来呈现Wiki网页?
89 0
重学前端 5 # 如何运用语义类标签来呈现Wiki网页?
|
小程序 UED 开发者
小程序开发必备功能的吐血整理【个人中心界面样式大全】
小程序开发必备功能的吐血整理【个人中心界面样式大全】
428 1
小程序开发必备功能的吐血整理【个人中心界面样式大全】
|
前端开发 Python
【Django | 开发】面试招聘信息网站(处理产品细节和权限&美化页面样式)
【Django | 开发】面试招聘信息网站(处理产品细节和权限&美化页面样式)
【Django | 开发】面试招聘信息网站(处理产品细节和权限&美化页面样式)
|
小程序 API Android开发
小程序开发-第三章第四节点击查看大图,保存壁纸-全栈工程师之路-中级篇
小程序开发-第三章第四节点击查看大图,保存壁纸-全栈工程师之路-中级篇
127 0
小程序开发-第三章第四节点击查看大图,保存壁纸-全栈工程师之路-中级篇
|
XML 移动开发 前端开发
这16种原生函数和属性的区别,你真的知道吗? 精心收集,高级前端必备知识,快快打包带走
原生内置了很多API, 作用类似,却也有差千差万别,了解其区别,掌握前端基础,是修炼上层,成为前端高级工程师的必备知识,让我们一起来分类归纳,一起成长吧。
164 0
这16种原生函数和属性的区别,你真的知道吗? 精心收集,高级前端必备知识,快快打包带走