簡體   English   中英

如何將png文件轉換為Uint8Array?

[英]how to turn a png file into Uint8Array?

我使用html代碼的輸入從卡片組獲取圖像。 然后,我希望將照片傳遞給javascript函數,以將其轉換為Uint8Array。 我該怎么做?

我僅通過以下方式實施了收購

         <input type="file" name="myimage">

您可以使用File APIFileReader對象及其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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM