js图片格式转换(File、blob、二进制)
一、File转Blob
MDN文档 createObjectURL
<input type="file">
<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();
}

二、Blob转File
var imgBlob = Blob-<<格式图片>>
var imgFile = new 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');
}

浙公网安备 33010602011771号