[英]how to turn a png file into Uint8Array?
我使用html代码的输入从卡片组获取图像。 然后,我希望将照片传递给javascript函数,以将其转换为Uint8Array。 我该怎么做?
我仅通过以下方式实施了收购
<input type="file" name="myimage">
您可以使用File API的FileReader
对象及其readAsArrayBuffer
方法将其读取为ArrayBuffer
,然后使用该ArrayBuffer
创建一个Uint8Array
。 大致:
const fr = new FileReader();
fr.onload = () => {
// It worked
const array = new Uint8Array(fr.result);
// ...use the array here...
};
fr.onerror = () => {
// The read failed, handle/report it
};
fr.readAsArrayBuffer(yourInputElement.files[0]);
这是一个快速且肮脏的示例:如果选择一个文件,这将通过在PNG标头中查找数据来告诉您是PNG文件还是其他类型的文件:
const PNG_HEADER = Uint8Array.of(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A); document.getElementById("yourInput").addEventListener("change", function() { const fr = new FileReader(); const file = this.files[0]; let {name} = file; const x = name.lastIndexOf("\\\\"); if (x !== -1) { name = name.substring(x + 1); } fr.onload = () => { // It worked const array = new Uint8Array(fr.result); if (array.length >= PNG_HEADER.length && PNG_HEADER.every((byte, index) => byte === array[index])) { console.log(`${name} is a PNG`); } else { console.log(`${name} is not a PNG`); } }; fr.onerror = () => { // The read failed, handle/report it }; fr.readAsArrayBuffer(file); });
<input type="file" id="yourInput">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.