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;
}
相關文章
相關標籤/搜索