jQuery插件综合应用(四)头像设置

一、操作流程

会员点击头像设置,弹出一个层,在层中,有上传图片的按钮,用户点击按钮上传图片,图片在服务器端按大小压缩保存(方便剪切)。保存后,在前端显示,然后用户可修剪图片。选择图片区域,点击提交,保存修剪后的图片,图片保存后在当前页面头像区域显示图片。

使用的插件有:弹出层使用lightbox_me插件,上传文件使用blueimp插件,切割图片使用Jcrop插件。
插件的使用方法可以看下面的博文:

网站开发常用jQuery插件总结(16)图片修剪插件Jcrop
网站开发常用jQuery插件总结(17)上传插件blueimp
网站开发常用jQuery插件总结(二)弹出层插件Lightbox_me

在上面的三篇文章中,只是介绍了插件的使用。而在本文的测试中,与上面三个插件的使用是有区别的。主要区别在于
linghtbox_me:在弹出层后,需点击按钮关闭弹出层。
blueimp:上传后,对图片进行压缩。方便使用Jcrop修剪图片。
Jcrop:修剪图片时,动态显示缩略图。

测试用例图

二、代码实现

1.引用文件说明。主要是3个插件使用的文件。

<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<!--弹出层插件lightbox_me使用的插件-->
<script type="text/javascript" src="lightbox_me/jquery.lightbox_me.js"></script>
<!--blueimp上传插件使用的文件-->
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/jquery.fileupload.js"></script>
<script type="text/javascript" src="js/jquery.iframe-transport.js"></script>
<link href="css/jquery.fileupload.css" rel="stylesheet" type="text/css"/>
<!--修剪插件Jcrop使用的文件-->
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<link href="css/jquery.Jcrop.css" rel="stylesheet" type="text/css"/>

2.插件样式说明。css主要用于页面布局。定义了一个弹出层的样式,其它的都非常简单。有兴趣的可以在下方 下载”测试代码”。

Jcrop与lightbox_me插件使用的为默认样式。blueimp修改了默认样式,因为blueimp使用了bootstrap框架,所以在官方的demo中使用了bootstrap中的样式。在本次测试中,修改为自己的样式。主要代码

<div class="fileinput-button">
   <span><input type="button" value="上传图片" class="WhiteButton" id="UploadFile"/></span>
   <input id="fileupload" type="file" name="file"/>
</div>

按钮的样式,使用的自动生成的样式。

.WhiteButton {
        
    -moz-box-shadow:inset 0px 1px 0px 0px #ffffff;
    -webkit-box-shadow:inset 0px 1px 0px 0px #ffffff;
    box-shadow:inset 0px 1px 0px 0px #ffffff;
        
    background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #f6f6f6));
    background:-moz-linear-gradient(top, #ffffff 5%, #f6f6f6 100%);
    background:-webkit-linear-gradient(top, #ffffff 5%, #f6f6f6 100%);
    background:-o-linear-gradient(top, #ffffff 5%, #f6f6f6 100%);
    background:-ms-linear-gradient(top, #ffffff 5%, #f6f6f6 100%);
    background:linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f6f6f6',GradientType=0);
        
    background-color:#ffffff;
        
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
    border-radius:6px;
        
    border:1px solid #dcdcdc;
        
    display:inline-block;
    color:#666666;
    font-family:arial;
    font-size:15px;
    font-weight:bold;
    padding:6px 24px;
    text-decoration:none;
        
    text-shadow:0px 1px 0px #ffffff;
        
}
.WhiteButton:hover {
        
    background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #f6f6f6), color-stop(1, #ffffff));
    background:-moz-linear-gradient(top, #f6f6f6 5%, #ffffff 100%);
    background:-webkit-linear-gradient(top, #f6f6f6 5%, #ffffff 100%);
    background:-o-linear-gradient(top, #f6f6f6 5%, #ffffff 100%);
    background:-ms-linear-gradient(top, #f6f6f6 5%, #ffffff 100%);
    background:linear-gradient(to bottom, #f6f6f6 5%, #ffffff 100%);
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f6f6f6', endColorstr='#ffffff',GradientType=0);
        
    background-color:#f6f6f6;
}
.WhiteButton:active {
    position:relative;
    top:1px;
}

3.js代码说明。js代码主要涉及到弹出层,上传图片,修剪图片。

弹出层

$('#operation-box').lightbox_me({
    centered: true,
    closeClick: false, //必须点击按钮关闭
    closeEsc: true,
    onLoad: function () {
        $('#operation-box').find('input:first').focus();
    }
});
//关闭弹出层
$('#Cancel').click(function () {
    $('#operation-box').trigger('close');
});

上传图片

$('#fileupload').fileupload({
    replaceFileInput: false,
    dataType: 'json',
    url: '<%=ResolveUrl("upload.ashx") %>',
    add: function (e, data) {
        var re = /^.+.((jpg)|(png))$/i;
        $.each(data.files, function (index, file) {
            if (re.test(file.name)) {
                data.submit();
            }
        });
    },
    done: function (e, data) {
        $.each(data.result, function (index, file) {
            $('#result').html();
            picFile = 'images/' + file;
            $('#result').html('<img src="' + picFile + '" id="picresult"/>');
            //判断浏览器.ie浏览器直接绑定
            //其它浏览器,判断图片是否加载完毕。
            if ($.browser.msie) {
                bindJcrop(picFile);
            } else {
                if ($('#picresult').load(function () {
                    bindJcrop(picFile);
                }));
            }
            $('#picresult').load(function () {
                //alert('111');

            });

        });
    }

});
function bindJcrop(picPath) {
    picHeight = $('#picresult').height();
    picWidth = $('#picresult').width();
    $('#preview').attr('src', picPath);
    if ($("#preview").is(":visible") == false) {
        $('#preview').show();
    }

    $('#picresult').Jcrop({
        onChange: storeCoords,
        onSelect: storeCoords,
        aspectRatio: 1
    });
    $('#oper').html('<input type="button" value="修剪头像" class="WhiteButton" onclick="toCrop()"/>');
}

在上传图片后,初始化修剪功能时。遇到了问题。使用$(id).ready(function({})) chrome,firefox无法使用修剪功能,ie8可以。使用$(id).load(function({})) chrome,firefox可以使用修剪功能,但ie8不可以。主要原因是因为图片是否加载完毕,picHeight与picWidth必须赋值成功。所以我使用$.browser.msie判断浏览器类型,然后再初始化修剪功能。

修剪图片

//显示缩略图使用,并记录坐标与修剪图片的高与宽。
function storeCoords(c) {
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);
    //以下是动态显示缩略图使用
    var rx = 150 / c.w;
    var ry = 150 / c.h;
    var x, y, w, h;
    //picWidth,picHeight为上传图片后的高度、宽度。
    //必须使用。
    w = Math.round(rx * picWidth);
    h = Math.round(ry * picHeight);
    x = Math.round(rx * c.x);
    y = Math.round(ry * c.y);
    $('#preview').css({
         w + 'px',
        height: h + 'px',
        marginLeft: '-' + x + 'px',
        marginTop: '-' + y + 'px'
    });

};
function toCrop() {
    var x = $('#x').val();
    var y = $('#y').val();
    var w = $('#w').val();
    var h = $('#h').val();
    if ($.trim(x) == "" || $.trim(y) == "" || $.trim(w) == "" || $.trim(h) == "") {
        //console.log("数据不能为空!");
        return;
    }
    //ajax操作,提交数据到后台,修剪图片。
    var params = "x=" + x + "&y=" + y + "&w=" + w + "&h=" + h + "&filepath=" + picFile;
    $.ajax({
        type: "POST",
        url: "crop.ashx",
        data: params,
        success: function (html) {
            $('#portrait').attr('src', html);
        }
    });
}

4.asp.net代码说明。主要用于上传图片,修剪图片。

上传图片

if (context.Request.Files.Count > 0)
{
    var file = context.Request.Files[0];
    if (Path.GetExtension(file.FileName).ToLower() != ".jpg" || Path.GetExtension(file.FileName).ToLower() != "png")
    {
        string path = context.Server.MapPath("~/images");
        string filename = Path.Combine(path, file.FileName);
        //file.SaveAs(filename);
        using (System.Drawing.Image image = System.Drawing.Image.FromStream(file.InputStream))
        {
            //将图片尺寸压缩在保存,宽度最大为450,高度最大为520
            //按比例压缩
            PicHelper helper = new PicHelper(image, 520, 450);
            helper.CreateNewPic(filename);
        }
        //返回上传后的图片地址
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        var result = new { name = file.FileName };
        context.Response.Write(serializer.Serialize(result));
    }

}

修剪图片

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    string img = context.Server.MapPath(context.Request.Form["filepath"]);
    int w = Convert.ToInt32(context.Request.Form["w"]);
    int h = Convert.ToInt32(context.Request.Form["h"]);
    int x = Convert.ToInt32(context.Request.Form["x"]);
    int y = Convert.ToInt32(context.Request.Form["y"]);
    byte[] CropImage = CropImg(img, w, h, x, y);
    using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
    {
        ms.Write(CropImage, 0, CropImage.Length);
        using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
        {
            string saveTo = string.Format("images/crop/{0}.jpg", Guid.NewGuid().ToString().Replace("-", ""));
            CroppedImage.Save(context.Server.MapPath(saveTo), CroppedImage.RawFormat);
            context.Response.Write(saveTo);
        }
    }
}
static byte[] CropImg(string img, int width, int height, int x, int y)
{
    try
    {
        using (SD.Image OriginalImage = SD.Image.FromFile(img))
        {
            using (SD.Bitmap bmp = new SD.Bitmap(width, height))
            {
                bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
                using (SD.Graphics graphic = SD.Graphics.FromImage(bmp))
                {
                    graphic.SmoothingMode = SmoothingMode.AntiAlias;
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, width, height), x, y, width, height, SD.GraphicsUnit.Pixel);
                    MemoryStream ms = new MemoryStream();
                    bmp.Save(ms, OriginalImage.RawFormat);
                    return ms.GetBuffer();
                }
            }
        }
    }
    catch (Exception Ex)
    {
        throw (Ex);
    }
}

三、测试说明

开发环境:vs2010
测试环境 chrome,firefox,ie8+
测试代码下载地址:http://www.1100w.com/wp-content/uploads/2013/10/PortraitSetting.rar

原文地址:https://www.cnblogs.com/imlions/p/3381070.html