TypeArray、ArrayBuffer、Blob的相互轉換


websocket 可以指定接受數據為 ArrayBuffer

/* websocket的情況下二進制流的獲取 */
var svip = 'ws://127.0.0.1:8080';
var ws = new WebSocket(svip);
ws.binaryType = 'arraybuffer'
ws.onmessage = function (e) {
    var message = e.data;
}

Blob 轉 ArrayBuffer

const blob = new Blob();
blob.arrayBuffer().then((ab) => console.log(ab))

// 或者通過FileReader
const fr = new FileReader(); fr.onload = function(){ const arrayBuffer = this.result; } fr.readAsArrayBuffer(blob);

ArrayBuffer 轉 Blob

const ab = new ArrayBuffer(32);
const blob = new Blob([ab]); // 注意必須包裹[]

ArrayBuffer 轉 TypeArray

const ab = new ArrayBuffer(10);
const u8 = new Uint8Array(ab);
const u16 = new Uint16Array(ab);
const u32 = new Uint32Array(ab);
const i8 = new Int8Array(ab);
const i16 = new Int16Array(ab);
const i32 = new Int32Array(ab);
const f32 = new Float32Array(ab);
const i32 = new Float32Array(ab);

TypeArray 轉 ArrayBuffer

// Uint8Array 舉例,其他一致
const u8 = new Uint8Array();
const ab = u8.buffer;

Array 轉 ArrayBuffer

const arr = [1, 2, 3, 4, 5];
// 通過 TypeArray 來轉換
var u8 = new Uint8Array(arr); var ab = u8.buffer;

// 或者通過 DataView 來設置,通過遍歷數組來填充
const buffer = new ArrayBuffer(16); const view1 = new DataView(buffer);

arr.forEach((num, i) =>
view1.setInt8(i, num));
// 或者
const iter = arr.entries()
for(let [key, value] of iter) {
  view1.setInt8(key, value)
}

TypeArray、ArrayBuffer、Blob 轉數組

const arr = Array.from(/* TypeArray | ArrayBuffer | Blob */)

 

參考:http://shihuacivis.github.io/2015/12/29/20151229_arrayBuffer

 

TypeArray


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM