Bootstrap

base64转化字节流 js_JS 实现blob与base64互转

/**

* base64 to blob二进制*/

functiondataURItoBlob(dataURI) {var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; //mime类型

var byteString = atob(dataURI.split(',')[1]); //base64 解码

var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组

var intArray = new Uint8Array(arrayBuffer); //创建视图

for (var i = 0; i < byteString.length; i++) {

intArray[i]=byteString.charCodeAt(i);

}return newBlob([intArray], {type: mimeString});

}/**

*

* blob二进制 to base64

**/

functionblobToDataURI(blob, callback) {var reader = newFileReader();

reader.οnlοad= function(e) {

callback(e.target.result);

}

reader.readAsDataURL(blob);

}

Data URL格式

Data URI 的格式

data:[][;charset=][;base64],

第一部分是 data: 协议头,它标识这个内容为一个 data URI 资源。

第二部分是 MIME 类型,表示这串内容的展现方式,比如:text/plain,则以文本类型展示,image/jpeg,以 jpeg 图片形式展示,同样,客户端也会以这个 MIME 类型来解析数据。

第三部分是编码设置,默认编码是 charset=US-ASCII, 即数据部分的每个字符都会自动编码为 %xx,关于编码的测试,可以在浏览器地址框输入分别输入下面两串内容,查看效果:

// output: ä½ å¥½ -> 使用默认的编码展示,故乱码

data:text/html,你好

// output: 你好 -> 使用 UTF-8 展示

data:text/html;charset=UTF-8,你好

// output: 浣犲ソ -> 使用 gbk 展示(浏览器默认编码 UTF-8,故乱码)

data:text/html;charset=gbk,你好

// output: 你好 -> UTF-8 编码,内容先使用 base64 解码,然后展示

data:text/html;charset=UTF-8;base64,5L2g5aW9

第四部分是 base64 编码设定,这是一个可选项,base64 编码中仅包含 0-9,a-z,A-Z,+,/,=,其中 = 是用来编码补白的。

最后一部分为这个 Data URI 承载的内容,它可以是纯文本编写的内容,也可以是经过 base64编码 的内容。

很多时候我们使用 data URI 来呈现一些较长的内容,如一串二进制数据编码、图片等,采用 base64 编码可以让内容变得更加简短。而对图片来说,在 gzip 压缩之后,base64 图片实际上比原图 gzip 压缩要大,体积增加大约为三分之一,所以使用的时候需要权衡。

Example

base64 可为任意数据格式MIME,text/html,image/jpeg,image/png******

依图片png base64为例

//base64 转blob

var base64Str = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJYAAAB4CAIAAACfLZxHAAAgAElEQVR4AYy9B7hcVbkwvMruM3PmnJMGIYVQY0IKKUBCQiAUATGin1xQrxUQBPlQEUNHAoKiIBe9l4AUES9eQeqlhBIg9BSTQHpvJ8nJaXOm7L7XWt/zrnfO5CTg//yTeXb27Nmz99pv74de/oe3KKVEv/rvCCEIIf2P4DlEqs89jmcedL6iREqp9OUPOkFK+dmbwpUVXP+ztzjoyo0TpGKfe77qu07jTEqppFIppegBt2hcGa/T/3xCYP2NI/138PqN39afjhAqMqo+D26Nqx+0wwA6fSuqw4QQwnCNdP8RqogiTEmLcjNNU8ekle59X/nSGcaLL7xCqCSKESop4Y2tkhSPU6aIYrglGgT9QXbQMzQecv9xBiDe/7GPXD4fNH0r/uz5eOSzxyVhhFGqmKKSEa6opIoBACTF/YOOKwWk2f8R+i/vs8f/1X37rgH/9ztHKSmZkkSviRBGiKSUEwJHPm8LoN2PsH4XrV9TkfoTIY4IyQQxbIcQknfMak9Hy4Ci4eWaG5du3IwCVey/feM4AR6UelmadvrwceBj7EcYUHE/FmycRgj5XC7pe4QDGLQfgOrfN44owiTHte5HHqITbszUQailTCkh9dPtBz2uCpiz73H67/Tf77/+/vuNc+B5iQCeUpQyQhQlVFHC8MjnbAF7HPjnMy/GDLgFXElfgyj4RBURCeVMCCEdkyQWKzqGEAroVsGWE9wCBfc/wpRUrH5EKRCMfQ/b/7ERKLiW/ccRVX2PA4SByyJS6cUhvSpNtXUR1x/rDej03bE/yQPEFFApYUpp3lNS1p8CuFI1nqL+RMDksPw6TzRIk8IX+7mk/3EtR/dz1UHE3eA2PK6olET0X7/G9H5h+BlMEQq4abz245L1yVb9XX1t8KwGV4QkQvI0izKRSGWA7KSEEsoAWrAlIMoJboE2Afx1aU0JkwTYCg5ooDZ2EKuNj40dg3MUFC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