JS實現圖片base64轉blob對象,壓縮圖片,預覽圖片,圖片旋轉到正確角度

base64轉blob對象

/** 將base64轉換爲文件對象
 *  @param {String} base64 base64字符串
 * */
var convertBase64ToBlob = function(base64){
    var base64Arr = base64.split(',');
    var imgtype = '';
    var base64String = '';
    if(base64Arr.length > 1){
        //若是是圖片base64,去掉頭信息
        base64String = base64Arr[1];
        imgtype = base64Arr[0].substring(base64Arr[0].indexOf(':')+1,base64Arr[0].indexOf(';'));
    }
    // 將base64解碼
    var bytes = atob(base64String);
    //var bytes = base64;
    var bytesCode = new ArrayBuffer(bytes.length);
     // 轉換爲類型化數組
    var byteArray = new Uint8Array(bytesCode);
    
    // 將base64轉換爲ascii碼
    for (var i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i);
    }
   
    // 生成Blob對象(文件對象)
    return new Blob( [bytesCode] , {type : imgtype});
};

壓縮圖片

/** 壓縮圖片
 * @param {Object} file 上傳對象files[0]
 * @param {Object} options 壓縮設置對象
 * @param {Function} callback 回調函數
 * @result {Object} 返回blob文件對象
 * */
var compressImg = function(file,options,callback){
    var self = this;
    var imgname = file.name;
    var imgtype = (imgname.substring(imgname.lastIndexOf('.') + 1)).toLowerCase();
    if(imgtype == 'jpg' || imgtype == 'jpeg'){
        imgtype = 'image/jpeg';
    }else{
        imgtype = 'image/png';
    }
    // 用FileReader讀取文件
    var reader = new FileReader();
    // 將圖片讀取爲base64
    reader.readAsDataURL(file);
    reader.onload = function(evt){
        var base64 = evt.target.result;
        // 建立圖片對象
        var img = new Image();
        // 用圖片對象加載讀入的base64
        img.src = base64;
        img.onload = function () {
            var that = this,
                canvas = document.createElement('canvas'),
                ctx = canvas.getContext('2d');
            canvas.setAttribute('width', that.width);
            canvas.setAttribute('height', that.height);
            // 將圖片畫入canvas
            ctx.drawImage(that, 0, 0, that.width, that.height);
            
            // 壓縮到指定體積如下(M)
            if(options.size){
                var scale = 0.9;
                (function f(scale){
                    if(base64.length / 1024 / 1024 > options.size && scale > 0){
                        base64 = canvas.toDataURL(imgtype, scale);
                        scale = scale - 0.1;
                        f(scale);
                    }else{
                        callback(base64);
                        
                    }
                })(scale); 
            } else if(options.scale){
                // 按比率壓縮
                base64 = canvas.toDataURL(imgtype, options.scale);
                callback(base64);
            }
            
        }
    }
};

圖片預覽

/**
 * 圖片預覽
 * @param {Object} $fileInput 文件上傳file
 * @param {Object} $previewImg 預覽圖片的image元素
 */
function previewImg($fileInput, $previewImg) {
    $fileInput.onchange = function ($event) {
        var $target = $event.target;
        if ($target.files && $target.files[0]) {
            var reader = new FileReader();
            reader.onload = function(evt){
                $previewImg.src = evt.target.result;
            }
            reader.readAsDataURL($target.files[0]);
        }
    }
}

詳細圖片預覽可參考地址:《搞清Image加載事件(onload)、加載狀態(complete)後,實現圖片的本地預覽,並自適應於父元素內(完成)javascript

圖片旋轉到正確的角度(驗證可行)

/**
 * 將圖片旋轉到正確的角度
 * (解決移動端上傳的圖片角度不正確的問題)
 * (旋轉後返回的是base64,能夠參照本目錄下的convertBase64ToBlob.js,將base64還原爲file input讀取獲得的文件對象)
 * @param {Dom Object} $fileInput 文件上傳輸入框
 * @param {Function} callback 旋轉完成後的回調函數
 */
function resetImgOrientation($fileInput, callback) {
    // 綁定change事件
    $fileInput.onchange = function ($event) {
        var $target = $event.target;
        if ($target.files && $target.files[0]) {
            // 獲取圖片旋轉角度
            getOrientation($target.files[0], function (orientation) {
                var reader = new FileReader();
                reader.readAsDataURL($target.files[0]);
                reader.onload = function(evt){
                    var base64 = evt.target.result;
                    // 將圖片旋轉到正確的角度
                    resetOrientation(base64, orientation, function (resultBase64) {
                        callback(resultBase64);
                    });
                }
            });
        }
    }
}

// 獲取圖片旋轉的角度
function getOrientation(file, callback) {
    var reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = function(e) {
        var view = new DataView(e.target.result);
        if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
        var length = view.byteLength, offset = 2;
        while (offset < length) {
            var marker = view.getUint16(offset, false);
            offset += 2;
            if (marker == 0xFFE1) {
                if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
                var little = view.getUint16(offset += 6, false) == 0x4949;
                offset += view.getUint32(offset + 4, little);
                var tags = view.getUint16(offset, little);
                offset += 2;
                for (var i = 0; i < tags; i++)
                    if (view.getUint16(offset + (i * 12), little) == 0x0112)
                        return callback(view.getUint16(offset + (i * 12) + 8, little));
            }
            else if ((marker & 0xFF00) != 0xFF00) break;
            else offset += view.getUint16(offset, false);
        }
        return callback(-1);
    };
}
// 將圖片旋轉到正確的角度
function resetOrientation(srcBase64, srcOrientation, callback) {
    var img = new Image();
    img.onload = function() {
        var width = img.width,
            height = img.height,
            canvas = document.createElement('canvas'),
            ctx = canvas.getContext("2d");
        // set proper canvas dimensions before transform & export
        if ([5,6,7,8].indexOf(srcOrientation) > -1) {
            canvas.width = height;
            canvas.height = width;
        } else {
            canvas.width = width;
            canvas.height = height;
        }
        // transform context before drawing image
        switch (srcOrientation) {
            case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
            case 3: ctx.transform(-1, 0, 0, -1, width, height ); break;
            case 4: ctx.transform(1, 0, 0, -1, 0, height ); break;
            case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
            case 6: ctx.transform(0, 1, -1, 0, height , 0); break;
            case 7: ctx.transform(0, -1, -1, 0, height , width); break;
            case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
            default: ctx.transform(1, 0, 0, 1, 0, 0);
        }
        // draw image
        ctx.drawImage(img, 0, 0);
        // export base64
        callback(canvas.toDataURL('image/jpeg'));
    };
    img.src = srcBase64;
};

參考地址:html

file上傳圖片,base64轉換、壓縮圖片、預覽圖片、將圖片旋轉到正確的角度
H5圖片壓縮與上傳java

Accessing JPEG EXIF rotation data in JavaScript on the client sidecanvas

相關文章
相關標籤/搜索