Published
Edited
Jun 9, 2020
Insert cell
md`
# Blob介绍
参考:
1. https://zh.javascript.info/blob
2.
`
Insert cell
md` ## Blob语法`
Insert cell
md`- 基础用法`
Insert cell
md`
\`\`\`
new Blob(blobParts, options);
\`\`\`
- blobParts 是 Blob/BufferSource/String 类型的值的数组。
- options 可选对象:
- type —— Blob 类型,通常是 MIME 类型,例如 image/png,
- endings —— 是否转换换行符,使 Blob 对应于当前操作系统的换行符(\r\n 或 \n)。默认为 "transparent"(啥也不做),不过也可以是 "native"(转换)。
`
Insert cell
{
// 从类型化数组(typed array)和字符串创建 Blob
let hello = new Uint8Array([72, 101, 108, 108, 111]); // 二进制格式的 "hello"
let blob = new Blob([hello, ' ', 'world'], {type: 'text/plain'});
}
Insert cell
md`- 用 slice 方法来提取 Blob 片段`
Insert cell
md`我们无法直接在 Blob 中更改数据,但我们可以通过 slice 获得 Blob 的多个部分,从这些部分创建新的 Blob 对象,将它们组成新的 Blob,等。`
Insert cell
md`
\`\`\`
blob.slice([byteStart], [byteEnd], [contentType]);
\`\`\`
- byteStart —— 起始字节,默认为 0。
- byteEnd —— 最后一个字节(专有,默认为最后)。
- contentType —— 新 blob 的 type,默认与源 blob 相同。
`
Insert cell
md`## Blob用途`
Insert cell
md`- Blob用作URL`
Insert cell
html `<a download="hello.text" href="#" id="link">Download</a>`
Insert cell
blob = new Blob(["hello,world"],{type:"text/plain"});
Insert cell
Insert cell
link.href = URL.createObjectURL(blob);
Insert cell
URL.revokeObjectURL(link.href);// 释放内存
Insert cell
md`- Blob转Base64`
Insert cell
{
let blob = new Blob(['Hello, world!'], {type: 'text/plain'});
let reader = new FileReader();
reader.readAsDataURL(blob); // 将 Blob 转换为 base64 并调用 onload
return reader;
}
Insert cell
md`- Image转Blob`
Insert cell
{
const img = document.createElement('img')
// 生成同尺寸的 <canvas>
let canvas = document.createElement('canvas');
canvas.width = img.clientWidth;
canvas.height = img.clientHeight;
let context = canvas.getContext('2d');
// 向其中复制图像(此方法允许剪裁图像)
context.drawImage(img, 0, 0);
// 我们 context.rotate(),并在 canvas 上做很多其他事情
// toBlob 是异步操作,结束后会调用 callback
canvas.toBlob((blob)=>{console.log('callback');})
}
Insert cell
md`- Blob转ArrayBuffer`
Insert cell
{
// 从 blob 获取 arrayBuffer
let fileReader = new FileReader();
fileReader.readAsArrayBuffer(blob);
fileReader.onload = function(event) {
let arrayBuffer = fileReader.result;
};
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more