在 JS 中将 ImageData 转换为 blob?

Convert ImageData to blob in JS?

我有一个 ImageData 对象,但 Tesseract.js 只需要 blob 个对象。如何尽可能高效地将 ImageData 转换为 blob

Tesseract.js 还采用其他一些类型 - https://github.com/naptha/tesseract.js/blob/master/docs/image-format.md - 我在互联网上找到了一些代码来转换:

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

引用 here,代码应该类似于 -

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