将缓冲区作为 Uint8Array 传递,不带空字节

Mar*_*in3 6 javascript tesseract node.js

我试图通过缓冲区将图像数据从Jimp图像对象传递到 Tesseract (ocr lib):

image.getBufferAsync('image/png').then((buffer) => {
  // Buffer here is <Buffer 12 34 56 ...
  const worker = new TesseractWorker();
  worker.recognize(buffer)
      .then((result) => { console.log('result', result.text); });

});
Run Code Online (Sandbox Code Playgroud)

Teserract 抛出一个错误,表示它需要 Uint8Array 而不是 buffer

TypeError [ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes. Received <Buffer 89 50 4e 47...
Run Code Online (Sandbox Code Playgroud)

所以我尝试将 buffer 转换为 Uint8Array:

buffer = new Uint8Array(buffer);
Run Code Online (Sandbox Code Playgroud)

但我收到另一个错误:

TypeError [ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes. Received Uint8Array [
  137,
  80,
  ...
Run Code Online (Sandbox Code Playgroud)

哪里有错误呢?


如果我将图像文件保存到光盘,然后通过 Teserrat 读取其路径 - 它可以工作,所以问题不应该是图像。

Cha*_*lie 0

文档指出,在 Node JS 中,img参数应该是本地图像的路径。

在浏览器上,图像可以是:

  • img、视频或画布元素
  • 一个 File 对象(来自文件)
  • 可访问图像的路径或 URL

在 Node.js 中,图像可以是

  • 本地图像的路径

https://github.com/naptha/tesseract.js/blob/master/docs/image-format.md

这意味着库希望自己读取文件,而不是提供字节流进行分析。