js上传图片压缩,并转化为base64

<input type="file"   onchange="startUpload(this,'front')"  id="renm"/>
<input type="hidden"   id="front" name="front"/>
 
   
function startUpload(fileId,site){
    var this_=$(fileId);
    var front;
    if(site=='back' || site=='head'){
        front=$('#front').val();
        if(front.length==0){
            layer.msg('请先上传身份证正面照');
            return;
        }
    }
    readAsDataURL( fileId,function(img){
        this_.prev().attr({src : img});
        this_.show();
        this_.next().val(img);
        });
}


/**
 * 读取图片为base64数据 返回 base64图片
 * @param file 文件
 * @param callback 回调函数
 */
function readAsDataURL(fileId,callback){
    var file = $(fileId).get(0).files[0];
    var reader = new FileReader();
    var image = new Image();
    var canvas = createCanvas();
    var ctx = canvas.getContext("2d");
    reader.onload = function(){ // 文件加载完处理
        var result = this.result;
        image.onload = function(){ // 图片加载完处理
            var imgScale = imgScaleW(800,this.width,this.height);
            canvas.width = imgScale.width;
            canvas.height = imgScale.height;
            ctx.drawImage(image,0,0,imgScale.width,imgScale.height);
            var dataURL = canvas.toDataURL('image/jpeg'); // 图片base64
            ctx.clearRect(0,0,imgScale.width,imgScale.height); // 清除画布
            callback (dataURL); //dataURL:处理成功返回的图片base64
        };
        image.src = result;
    };
    reader.readAsDataURL(file);
}
/**
 *  创建画布
 * @returns
 */
function createCanvas(){
    var canvas = document.getElementById('canvas');
    if(!canvas){
        var canvasTag = document.createElement('canvas');
        canvasTag.setAttribute('id','canvas');
        canvasTag.setAttribute('style','display:none;');//隐藏画布
        document.body.appendChild(canvasTag);
        canvas = document.getElementById('canvas');
    }
    return canvas;
}
/**
 * 图片压缩
 * @param maxWidth 最大宽度或最大高度
 * @param width 宽度
 * @param height 高度
 * @returns {___anonymous1968_1969}
 */
function imgScaleW(maxWidth,width,height){
    var imgScale = {};
    var w = 0;
    var h = 0;
    if(width <= maxWidth && height <= maxWidth){ // 如果图片宽高都小于限制的最大值,不用缩放
        imgScale = {
                width:width,
                height:height
        };
    }else{
        if(width >= height){ // 如果图片宽大于高
            w = maxWidth;
            h = Math.ceil(maxWidth * height / width);
        }else{     // 如果图片高大于宽
            h = maxWidth;
            w = Math.ceil(maxWidth * width / height);
        }
        imgScale = {
                width:w,
                height:h
        };
    }
    return imgScale;
}

 

转载于:https://www.cnblogs.com/zhaoyan001/p/10348411.html

你可能感兴趣的:(js上传图片压缩,并转化为base64)