我正在尝试将 canvas.toBlob 输出保存在 PNG 文件中,但输出似乎不是有效的 PNG(尽管它很接近)。第 1 个 4 字节应该是(十六进制)“89 50 4e 47”。相反,我得到了“ff fd 50 4e 47”,即不是“89”而是“ff fd”。当我尝试打开 PNG 文件时,Paint 等应用程序说它无效。下面的示例显示输出到控制台的格式,但不保存文件。
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillRect(25, 25, 100, 100);
canvas.toBlob(function(blob) {
const reader = new FileReader();
reader.addEventListener('loadend', (e) => {
var result = e.srcElement.result;
var hex = StrToHex(result);
console.log(`result=${result}`);
console.log(`hex=${hex}`);
});
reader.readAsText(blob);
});
没有编码参数的FileReader.readAsText将使用编码读取您的 Blob UTF-8
。
也就是说,字节89 50 4e 47
变成了字符串�PNG
。你在这里做的是从这个字符串中获取十六进制,它与原始字节值不同:
// build a Blob from this hex string
const originalStrHex = '89 50 4e 47';
const hexAsUint8 = originalStrHex
.split(' ')
.map((v) => parseInt(v, 16));
const bytes= Uint8Array.from(hexAsUint8);
const reader = new FileReader();
reader.readAsText(new Blob([bytes]));
reader.onload = e => {
const res = reader.result;
console.log(res);
const fromUTF8 = new TextEncoder().encode(res);
const strHex = [...fromUTF8]
.map(v => v.toString(16).padStart(2, "0"))
.join(' ');
// if that was correct, we should have had the same as originalStrHex
console.log(strHex);
};
所以,很可能,你的 Blob 是正确的。
您想要的只是将其作为 ArrayBuffer而不是 UTF-8 字符串读取:
document.createElement('canvas').toBlob(handleBlob);
function handleBlob(fullblob) {
const blob = fullblob.slice(0, 4);
const reader = new FileReader();
reader.onload = e => {
const view = new Uint8Array(reader.result);
const strHex = [...view].map(v => v.toString(16).padStart(2, "0")).join(' ');
console.log(strHex);
};
reader.readAsArrayBuffer(blob);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句