0

我目前正在尝试将 base64Encoded 字符串(图像的表示)转换为 Javascript 中的 ImageData 对象。但是,这会返回一个错误:

未捕获的 InvalidStateError:无法构造“ImageData”:输入数据长度不是 4 的倍数。

编码图像为 940 x 740

我错过了什么?任何帮助表示赞赏

带有完整代码的 JSFiddle 链接

   function _base64ToArrayBuffer(base64) {
        var binary_string = window.atob(base64);
        var len = binary_string.length;
        var bytes = new Uint8Array(len);
        for (var i = 0; i < len; i++) {
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes.buffer;
    }


const base64String = ""; //truncated because stackoverflow question too long.
const arrBuffer = _base64ToArrayBuffer (base64String );

var array = new Uint8ClampedArray(arrBuffer);
console.log(array);
var image = new ImageData(array, 900, 740);
console.log(image);
4

1 回答 1

0

您可以从 Canvas 获取 ImageData

function _base64ToImageData(buffer, width, height) {
    return new Promise(resolve => {
    var image = new Image();
    image.addEventListener('load', function (e) {
      var canvasElement = document.createElement('canvas');
      canvasElement.width = width;
      canvasElement.height = height;
      var context = canvasElement.getContext('2d');
      context.drawImage(e.target, 0, 0, width, height);
      resolve(context.getImageData(0, 0, width, height));
    });
    image.src = 'data:image/png;base64,' + buffer;
    document.body.appendChild(image);
    setTimeout(() => {
      document.body.removeChild(image);
    }, 1);
  });
}

window.addEventListener('load', () => {
  _base64ToImageData(base64String, 2056, 1236).then(data => {
    console.log(data);
  });
});
于 2021-07-23T09:05:54.267 回答