layui图片上传前使用canvas压缩并添加文字水印方法小结

公司项目用户注册要上传身份证照片等隐私资料,为了给用户信息多加一道保险,使用canvas对图片添加文字水印后再上传到七牛云。前端不太熟,好不容易做出来,如有冗余或不完善之处,发现的朋友请不吝指教。

layui使用js上传七牛云html代码:



*身份证正面:

layui通过后台上传图片html代码:
    
    

layui通过后台上传图片jq代码:

                upload.render({
                    elem: '#idz_pic'
                    , url: domain + "/wenhu/v1.img/oneUploadImg1?name=" + name + '&nn=legal_cerificate_front'
                    , auto: false
                    , bindAction: $('#idz_pic').prev("input")
                    , choose: function (obj) {

                        //预读本地文件,如果是多文件,则会遍历。(不支持ie8/9)
                        obj.preview(function(index, file, result){
                            newCanvas(obj, index, file, $('#idz_pic'));
                        });

                    }
                    , done: function (res, index, upload) { //上传后的回调
                        // console.log(res);
                        layer.close(layer.index, {isOutAnim: true});
                        setTimeout(function () {
                            if (res.code == 200) {
                                $('#idz_pic').hide();
                                var pic = $('input[name=idz_pic]').val();
                                if (pic == "") {
                                    $('input[name=idz_pic]').val(res.data);
                                    $('#idz span img').attr("src", res.data);
                                    $('#idz span').show();
                                }
                                layer.msg(res.msg, {icon: 6});
                            } else {
                                layer.msg(res.msg, {icon: 5});
                            }
                        }, 1000);
                    }
                    , accept: 'images'
                    , field: 'imgfile'
                    , size: 2048
                    , before: function () {
                        var index = layer.load(1);  //上传前
                    }
                });

上传相关方法、canvas图片压缩及文字水印方法:

/**
 * 七牛云上传相关方法、canvas图片压缩及文字水印方法
 */

/*layui前端js上传图片,Canvas处理*/
$('.select3').change(function () {

    var that = $(this);
    var file = this.files[0];
    var key = 'img' + (new Date()).valueOf();

    var putExtra = {
        fname: "",
        params: {},
        mimeType: ["image/png", "image/jpeg", "image/gif"]
    };

    /*上传前,Canvas处理压缩、添加水印*/
    getCanvasBlob(file, that, function (blob) {

        blob.name = file.name;
        blob.uid = file.uid;

        var observable = qiniu.upload(blob, key, getToken(), putExtra);

        /*上传开始*/
        var observer = {
            next: function (res) {
                /*console.log(res);*/
                that.next("p").text("进度:" + res.total.percent + "% ");
            },
            error: function (res) {
                console.log(res);
                if (res.code != 200) {
                    layer.msg("上传出现异常,请检查上传文件类型是否png、jpeg或gif格式");
                }
            },
            complete: function (res) {
                console.log(res);
                if (res.key != undefined && res.key != '') {
                    that.next("p").next("img").attr('src', getImgUrl(res.key));
                    that.prev("input").val(res.key);
                    that.prev("input").prev("button").text('重新上传');
                }
            }
        };
        var subscription = observable.subscribe(observer);

        /*上传取消*/
        /*subscription.unsubscribe();*/

    });

});

/*Canvas处理方法*/
function getCanvasBlob(file, that, blob) {

    var reader = new FileReader();
    var img = document.createElement('img');
    reader.readAsDataURL(file);
    reader.onload = function (e) {
        img.src = e.target.result
    };

    var canvas = document.createElement('canvas');
    img.onload = function () {
        var context = canvas.getContext('2d');

        /*图片压缩*/
        compress(canvas, context, img, this.width, this.height);

        /*图片文字水印*/
        if (that.data('watermake') == true) watermake(context, that.data('text'));

        /*canvas 转为 blob 并上传:*/
        canvas.toBlob(blob, file.type || "image/jpeg", 0.95);

    };

}

/*
* layui通过后台上传图片,Canvas处理
* 也可直接调用getCanvasBlob()方法,灵活地在回调中处理更多业务
*/
function newCanvas(obj, index, file, that) {

    /*上传前,Canvas处理压缩、添加水印*/
    getCanvasBlob(file, that, function (blob) {

        blob.name = file.name;
        blob.uid = file.uid;

        obj.resetFile(index, blob, file.name);
        that.prev("input").trigger("click");

    });

}

/*图片压缩*/
function compress(canvas,context, img, originWidth, originHeight) {
    // 目标尺寸
    var targetWidth = originWidth;
    var targetHeight = originHeight;
    // 最大尺寸限制
    var maxWidth = 1500;
    var maxHeight = 1500;

    if (originWidth > maxWidth || originHeight > maxHeight) {
        if (originWidth / originHeight > maxWidth / maxHeight) {
            // 更宽,按照宽度限定尺寸
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth))
        } else {
            targetHeight = maxHeight;
            targetWidth = Math.round(maxHeight * (originWidth / originHeight))
        }

    }

    // canvas 对图片进行缩放
    canvas.width = targetWidth;
    canvas.height = targetHeight;
    // 清除画布
    context.clearRect(0, 0, targetWidth, targetHeight);
    // 图片压缩
    context.drawImage(img, 0, 0, targetWidth, targetHeight);

}

/*文字水印
* context,HTML5对象,拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。
* text,自定义水印方案
*/
function watermake(context, text) {
    /*默认水印方案*/
    if (text == undefined) text = '仅供问虎平台开户使用';

    for (var i = 0; i < 20; i++) {
        /*水印初始偏转角度*/
        context.rotate(-15 * Math.PI / 180);
        /*字号、字体*/
        context.font = "28px 黑体";
        /*颜色、透明度*/
        context.fillStyle = "rgba(100,100,100, .6)";
        for (var j = 0; j < 6; j += 1) {
            /*水印文字,可自定义*/
            context.fillText(text, -800 + j * 420, i * 200)
        }
        context.rotate(15 * Math.PI / 180);
    }

}

/*获取图片链接接口:*/
function getToken() {
    var i;
    $.ajax({
        async: false, /*同步*/
        type: 'GET',
        url: '/api/v1.img/getToken',
        success: function (res) {
            /*console.log(res);*/
            i = res.data.token;
        }
    });
    return i;
}

/*获取图片链接接口:*/
function getImgUrl(key) {
    var i;
    /*var i = "存在无效的文件Key或其它异常";*/
    $.ajax({
        async: false, /*同步*/
        type: 'GET',
        url: '/api/v1.img/getFiles?file_keys=' + key,
        success: function (res) {
            if (res.data == undefined) {
                console.log(res.message);
            } else {
                i = res.data[0].file_url;
            }
        }
    });
    return i;
}


 

你可能感兴趣的:(canvas,前端)