0
点赞
收藏
分享

微信扫一扫

js图片格式转换(File、blob、二进制)

穆风1818 2022-10-30 阅读 193

一、File转Blob

​​MDN文档 createObjectURL​​​​​​

<button class="btn" onclick="openFile()">点我</button>

function openFile() {
var input = document.createElement('input');
input.type = 'file';
input.onchange = e => {
var imgFile = e.target.files[0];
var imgBlob = URL.createObjectURL(imgFile );
console.log('imgFile',imgFile);
console.log('imgBlob',imgBlob);
}
input.click();
}

js图片格式转换(File、blob、二进制)_2d

二、Blob转File

​​MDN文档 File​​使用js将blob对象转file对象

var imgBlob = Blob-<<格式图片>>

var imgFile = new window.File([imgBlob], Math.random(), {
type: imgBlob.type,
});

三、Blob转二进制(base64)

// 获取 img 的 dom
function base64 (dom) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = dom.width;
canvas.height = dom.height;
ctx?.drawImage(dom, 0, 0, dom.width, dom.height);
return canvas.toDataURL('image/png');
}

箴言:因为这些东西是非常简单的。不要抱怨自己学不会,那是因为你没有足够用心。



举报

相关推荐

0 条评论