概述
graph TD
b[ 字符串 ] -.Blob.-> a[ blob ]
c[ 图片url ] -.XMLHttpRequest.-> a[ blob ]
d[ 图片base64 ] -.ArrayBuffer + Blob.-> a[ blob ]
e[ 图片由input框获取 ] -.Blob.-> a[ blob ]
a[ blob ] -.URL.createObjectURL.-> f[ localUrl ]
a[ blob ] -.URL.createObjectURL.-> g[ arraybuffer ]
g[ arraybuffer ] -.Blob.-> a[ blob ]
资源转blob
字符串转blob
比如你有个拼接而成的html字符串,想将它转成blob,则可以这么做
const html = `<div>nihao</div>`
let blob = new Blob([html], { type: 'text/html' })
图片url转blob
比如你知道了图片的url,但是想要获取它的blob方便用来上传图片,则可以这么做。
注意
:图片必须是支持跨越或者同源,否则不行。如果硬要解决这个问题,则可以通过让服务端写一个接口进行转发,让服务端同学将图片转成支持跨域即可。
function httpGetImgBlog(url) {
return new Promise((res, rej) => {
let xhr = new XMLHttpRequest();
xhr.open("get", scaleImg(url), true)
xhr.responseType = "blob"
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 400) {
res(xhr.response)
}
}
xhr.send();
})
}
图片base64转blob
比如你知道了图片的url但是为base64,但是想要获取它的blob方便用来上传图片,则可以这么做。
function imgBase64ToBlob(base64) {
var type = base64.split(",")[0].match(/:(.*?);/)[1];//提取base64头的type如 'image/png'
var bytes = window.atob(base64.split(',')[1]);//去掉url的头,并转换为byte (atob:编码 btoa:解码)
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);//通用的、固定长度(bytes.length)的原始二进制数据缓冲区对象
//var ia = new Uint8Array(bytes.length);
for (var i = 0; i < bytes.length; i++) {
ab[i] = bytes.charCodeAt(i);
}
let blob = new Blob([ab], { type: type });
return blob
}
图片由input上传转blob
function fileToBlob(file) {
return new Blob([file])
}
blob的应用
blob转localUrl
let localUrl = URL.createObjectURL(blob)
blob与arraybuffer互转
// arraybuffer 转 blob
let blob = new Blob([arraybuffer])
// blob转arraybuffer
function blob2arraybuffer(blob) {
return new Promise((res, rej) => {
var reader = new FileReader()
reader.readAsArrayBuffer(blob)
reader.onload = function () {
res(this.result)
}
})
}