ba_
ba_

Reputation: 15

Tesseract.js does not work on local files

When I run tesseract.js on a URL it works fine. But when I run it on a local file I get these errors. How can I solve this?

I am running tesseract.js v2.1.0 and here is my code:

const { createWorker } = require('tesseract.js');

const worker = createWorker({
  logger: m => console.log(m), // Add logger here
});

(async () => {
  await worker.load();
  await worker.loadLanguage('eng');
  await worker.initialize('eng');
  const { data: { text } } = await worker.recognize('download.png');
  console.log(text);
  await worker.terminate();
})();

enter image description here

Upvotes: 0

Views: 1576

Answers (1)

Porush Manjhi
Porush Manjhi

Reputation: 164

If you want to load local images in tesseract you have to load them via input tag, Here is the working example.

HTML

<input type="file" id="input_image" accept="image/*">

JavaScript

const input_image = document.getElementById("input_image");

const offscreen_canvas = new OffscreenCanvas(0, 0);
const offscreen_canvas_context = offscreen_canvas.getContext("2d");

input_image.addEventListener("change", () => {
  var file = input_image.files[0];
  if (file == undefined) return;
  var reader = new FileReader();
  reader.onload = function (event) {
    const reader_image = event.target.result;
    const image = new Image();
    image.onload = function () {
      offscreen_canvas.width = image.width;
      offscreen_canvas.height = image.height;
      offscreen_canvas_context.drawImage(image, 0, 0);
      offscreen_canvas.convertToBlob().then((blob) => {
        Tesseract.recognize(blob, "eng", {
          logger: (m) => console.log(m)
        }).then(({ data: { text } }) => {
          console.log(text);
        });
      });
    };
    image.src = reader_image;
    };
  reader.readAsDataURL(file);
});

Upvotes: 0

Related Questions