1. 程式人生 > >html裁剪頭像成base64+ashx儲存圖片到本地

html裁剪頭像成base64+ashx儲存圖片到本地

CSS 引用  https://code.csdn.net/snippets/2270112/master/imgCut.css/raw

JS 引用 https://code.csdn.net/snippets/2270138/master/imgCut.js/raw

JS

var frameY, frameX, frameW, frameH;//全域性變數
var ifCutBox = false;
$(document).ready(function () {
            init();//初始化
});
function clacImgZoomParam(maxWidth, maxHeight, width, height) {
            var param = { top: 0, left: 0, width: width, height: height };
            if (maxWidth) {
                rateWidth = width / maxWidth;
                rateHeight = height / maxHeight;
                if (rateWidth > rateHeight) {
                    param.width = maxWidth;
                    param.height = Math.round(height / rateWidth);
                    rate = rateWidth;
                } else {
                    param.width = Math.round(width / rateHeight);
                    param.height = maxHeight;
                    rate = rateHeight;
                }
            }
            return param;
        };
        selectrate = 1;
        rate = 1;   
        function preview(img, selection) {
            if (!selection.width || !selection.height)
                return;
            var img = $("#view_photo");
            var scaleX = $("#preview").width() / selection.width;
            var scaleY = $("#preview").height() / selection.height;

            $('#preview img').css({
                width: Math.round(scaleX * $("#photo").width()),
                height: Math.round(scaleY * $("#photo").height()),
                marginLeft: -Math.round(scaleX * selection.x1),
                marginTop: -Math.round(scaleY * selection.y1)
            });

            frameX=Math.round(selection.x1 * rate);
            frameY=Math.round(selection.y1 * rate);
            frameW=Math.round(selection.width * rate);
            frameH=Math.round(selection.height * rate);
        }
        function init() {
            var width = $('#photo').width();
            var height = $('#photo').height();
            $('#photo').imgAreaSelect({
                aspectRatio: "1:1",
                handles: true,
                fadeSpeed: 200,
                onSelectChange: preview,

            });
        }
        function change(file) {
            $.each($('#upload')[0].files, function (i, file_) {
                if ("image/png" == file_.type || "image/jpeg" == file_.type) {
                    if (102400 < file_.size) {
                        layer.msg("頭像上傳失敗!不能大於100KB");
                        return;
                    }
                    var files = !!file.files ? file.files : [];
                    if (!files.length || !window.FileReader) return;
                    if (!ifCutBox) {
                        $("#UserC_Box").append('<div class="frame">' +
                                '<img id="photo" ></div>' +
                            '<div id="preview">' +
                                '<img id="view_photo"></div>' +
                            '<div id="saveBtn" onclick="saveH()">儲存頭像</div>');
                        ifCutBox = true;
                    }
                    var reader = new FileReader();
                    reader.readAsDataURL(files[0]);
                    reader.onloadend = function () {
                        var img = $('#photo');
                        img.attr("src", this.result);
                        $("#view_photo").attr("src", this.result);
                        img.load(function () {
                            var img = $('#photo');
                            img.width('100%');
                            img.height('100%');
                            var rect = clacImgZoomParam(300, 300, img.width(), img.height());
                            img.width(rect.width);
                            img.height(rect.height);
                            $("#preview").width(80);
                            $("#preview").height(80);
                            init();
                        });
                    }
                } else {
                    layer.msg("請選擇正確的檔案格式!jpg或png");
                    return;
                }
            })
        };
        function saveH() {
            if (!ifCut) { return layer.msg("請選擇裁剪區域!"); }
            var crop_canvas, width = 120, height = 120;
            crop_canvas = document.createElement('canvas');
            crop_canvas.width = width;
            crop_canvas.height = height;
            var img = document.getElementById("view_photo");
            crop_canvas.getContext('2d').drawImage(img, frameX, frameY, frameW, frameH, 0, 0, width, height);
            var index = layer.msg("上傳中...", { icon: 16, time: false, shade: [0] });
            var strUrl,strData,imgH64=crop_canvas.toDataURL("image/png");
            imgH64 = imgH64.substring(22, imgH64.length);
            strUrl = "handler/JqDataHandle.ashx?RemoteName=Ssh50h.Master";
            strData = "mode=saveHead&method=modifyH&parameters=2&parameters0=" + objParam.s1user + "&parameters1=" + encodeURIComponent(imgH64);
            $.ajax({
                type: "POST",
                url: strUrl,
                data: strData,
                dataType:"text",
                cache: false,
                async: false,
                success: function (data) {
                    layer.close(index);
                    if (data.substring(0, 5) == "Error") {
                        layer.msg(data.substring(6, data.length));
                        return;
                    }
                        layer.msg("頭像儲存成功!");
                        localStorage.setItem("SHMainPage", "1");
                        javascript: location.href = 'SHMainPage.aspx';
                        return;
                },
                error: function (err) {
                    layer.close(index);
                    layer.msg("抱歉發生錯誤!請檢查網路狀況");
                    return;
                }
            })
        };

HTML

<div  id="UserC_Box"></div>

ASHX

public void saveHead(HttpContext context)
    {
        string result;
        string userID = context.Request.Form["parameters0"].ToString();
        string base64Str = context.Request.Form["parameters1"].ToString();
        base64Str = strDecode(context, base64Str);
        string headPath =context.Server.MapPath("~/saveHead/"+userID+".jpg");
        byte[] byteHead = Convert.FromBase64String(base64Str);
        try { System.IO.File.WriteAllBytes(headPath, byteHead); } catch {result = "Error:錯誤程式碼01,儲存頭像失敗!";
        context.Response.Write(result);context.Response.End();return; }
        return ;
    }