Convert ImageData to blob in JS?

5.7k views Asked by At

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?

2

There are 2 answers

0
Nikhil Patil On BEST ANSWER

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
  });
}
0
AlexAndHisScripts On

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;
}