blob 文件转 url, base64 转 blob

URL.createObjectURL(blob)

这个方法便捷,且是同步的,但需要基于当前的内存,换句话说,这个 url 不能拿到其他页面使用。

let url = URL.createObjectURL(blob)

FileReader.readAsDataURL(blob)

这个方法是异步的,转化成 base64,可以放到其他页面使用。

let fr = new FileReader();
fr.readAsDataURL(blob);
fr.onload = function (e) {
console.log(e.target.result);
};

base64 转 blob

base64ToBlob(urlData, type) {
let arr = urlData.split(',');
let mime = arr[0].match(/:(.*?);/)[1] || type;
// 去掉url的头,并转化为byte
let bytes = window.atob(arr[1]);
// 处理异常,将ascii码小于0的转换为大于0
let ab = new ArrayBuffer(bytes.length);
// 生成视图(直接针对内存):8位无符号整数,长度1个字节
let ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], {
type: mime
});
}

截获视频的第一帧图片

生成的 video 一定要把 autoplay 属性设置为 true!!!!不然截获不了照片!

const captureVideoCover = (id, file) => {
const canvas = document.createElement("canvas");
const video = document.createElement("video");
video.autoplay = true;
video.src = URL.createObjectURL(file);
const handle = () => {
console.log(video.videoWidth, video.videoHeight);
canvas.width = video.videoWidth * 0.8;
canvas.height = video.videoHeight * 0.8;
console.log(canvas.width, canvas.height);
canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height);
const videoCoverURL = canvas.toDataURL("image/png", 1.0);
emit?.("getVideoCover", videoCoverURL);
video.removeEventListener("loadeddata", handle);
};
video.addEventListener("loadeddata", handle);
};