1

I have an ImageData object but Tesseract.js only takes blob objects. How can I convert the ImageData to a blob as performantly as possible?

  • Welcome to SO! This post appears to be [off-topic](http://stackoverflow.com/help/on-topic) as per *Questions that lack sufficient information to diagnose the problem.* Please edit your post accordingly to add sufficient detail so that people may help you. – Adhitya Dec 12 '20 at 10:29
  • What should I add? – AlexAndHisScripts Dec 12 '20 at 10:50

2 Answers2

2

Referring here, the code should look like -

const ImageDataToBlob = function(imageData){
  let w = imageData.width;
  let h = imageData.height;
  let canvas = document.createElement("canvas");
  canvas.width = w;
  canvas.height = h;
  let ctx = canvas.getContext("2d");
  ctx.putImageData(imageData, 0, 0);        // synchronous

  return new Promise((resolve) => {
        canvas.toBlob(resolve); // implied image/png format
  });
}
SColvin
  • 11,584
  • 6
  • 57
  • 71
Nikhil Patil
  • 2,480
  • 1
  • 7
  • 20
0

Tesseract.js also takes some other types - https://github.com/naptha/tesseract.js/blob/master/docs/image-format.md - and I have found some code on the internet to convert:

function imgDataToImage(imagedata) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = imagedata.width;
    canvas.height = imagedata.height;
    ctx.putImageData(imagedata, 0, 0);

    var image = new Image();
    image.src = canvas.toDataURL();
    return image;
}