首页 > 代码库 > ArrayBuffer and Base64

ArrayBuffer and Base64

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>ArrayBuffer and Base64</title>
</head>
<body>
    <img id="bbf" src="" />
    <img id="bbf2" src="" />
    <script>
    /**
     * Base64字符串转成ArrayBuffer数组 
     * @param {String} base64
     */
    function base64ToArrayBuffer(base64) {
        var binary_string =  window.atob(base64);
        var len = binary_string.length;
        var bytes = new Uint8Array(len);
        for (var i = 0; i < len; i++){
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes.buffer;
    }

    /**
     * ArrayBuffer数组转成Base64字符串 
     * @param {ArrayBuffer} buffer
     */
    function arrayBufferToBase64(buffer){
        var binary = ‘‘;
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++){
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa( binary );
    }

    window.onload = function(){
        var buff = base64ToArrayBuffer(base64Img.split(,)[1]);
        var _blob = new Blob([buff]);
        var imageURI = window.URL.createObjectURL(_blob);
        var imgobj = document.getElementById("bbf");
        imgobj.onload = function(){window.URL.revokeObjectURL(this.src);};//清除释放
        imgobj.setAttribute("src", imageURI);

        var imgobj = document.getElementById("bbf2");
        imgobj.setAttribute("src", base64Img);
    }
    var base64Img = "data:image/gif;base64,R0lGODlhGAAYAPfaAOtxR/FJAPdPAPlRAO5GAPNLAP/9/PtUAP6UW/RMAO9HAO1EAOY9AP/axuhAAPZOAOVGD/VNAPhQAPdOAO9GAPlSAOU9AOpBAPNKAP6WXutCAPpTAOlhM/+icOtiLvtrI/l0NPh0N+17U/ZyN/6sgf7s5P+whe9UFu15UOdGDPyMVPGZe/6tgfmIVPyRXedLE/lfFP6ERPdWC/6hb/d6QvJUD/JtNO1GA/+yieplOP1kEv7l2P6QWOpIC/VpK+ZRHf/v6PdsLf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