javascript - 我应该为图像文件的 ArrayBuffer 使用哪种类型数组?

标签 javascript html browser md5 typed-arrays

我正在使用 FileReader().readAsArrayBuffer() 读取图像文件,并使用 md5 库创建文件的哈希值。 readAsArrayBuffer() 返回一个 ArrayBuffer

const reader = new FileReader();

reader.onload = (event) => {
  // NEED TO CREATE TYPED ARRAY FROM
  const binary = new Uint8Array(event.target.result);
  const md5Hash = md5(binary);
};

reader.readAsArrayBuffer(imageFile);

来自 MDN ArrayBuffer

我们明白了:

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer.

It is an array of bytes, often refered to in other languages as a "byte array".

You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.

因此,我无法直接使用 md5 函数,我需要首先创建类型数组对象。

我的选择是:

  • Int8Array
  • Uint8Array
  • Int16Array
  • Int32Array

我应该在我的代码中使用以上哪一项?为什么?

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray

最佳答案

对此没有通用的答案,这基本上取决于消费者以及他们想要处理的格式。

例如,如果您想解析 PNG 的实际文件格式,您实际上需要能够以 BigEndian 顺序读取它的一些 block ,这意味着您在大多数个人计算机上都需要 DataView。

但是这里your library声称他们确实支持 Uint8Array 和 ArrayBuffer。但是,经过测试,它们似乎确实无法处理裸 ArrayBuffer,因此使用 Uint8Array,因为这就是您的库的文档所说的。

关于javascript - 我应该为图像文件的 ArrayBuffer 使用哪种类型数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56533552/

相关文章:

html - 在 CSS 中更改无序列表项的高度

html - 文本框上的自动填充(在 Chrome 中)会导致在不按输入的情况下进行预填充

javascript - 为什么 window.open() 不直接在 <script> 标签中工作?

javascript - 在 GWT 中使用第三方 javascript 库(带有窗口引用)

JavaScript:一张图像中的多重裁剪选择?

javascript - 将两个事件处理程序合并为一个?

html - CSS 列百分比无法按预期工作

javascript - ES6 构造函数返回基类的实例?

html 5查询自动文本大小

php - 浏览器不立即显示收到的套接字数据