本文介绍了从javascript中的画布中保存jpeg字节数组,而无需执行base64步骤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在使用它,但是如果可能的话,我想跳过base64转换步骤

Right now I'm using this, but I would like to skip the base64 conversion step if possible

function getJpegBytes()
{
 var jpgImg = canvas.toDataURL("image/jpeg");
    jpgImg = jpgImg.replace('data:image/jpeg;base64,', '');

    return _base64ToArrayBuffer(jpgImg);
}

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


推荐答案

使用,您可以获得,但它必须是异步的。然后,您可以将 Blob 转换为使用:

Using HTMLCanvasElement#toBlob(), you can get a Blob, but it will need to be asynchronous. Then you can convert the Blob to an ArrayBuffer using FileReader#readAsArrayBuffer():

function getJpegBytes(canvas, callback) {
  var fileReader = new FileReader()

  fileReader.addEventListener('loadend', function () {
    callback(this.error, this.result)
  })

  canvas.toBlob(fileReader.readAsArrayBuffer.bind(fileReader), 'image/jpeg')
}

然后您可以像这样执行它:

Then you can execute it like this:

getJpegBytes(document.querySelector('canvas'), function (error, arrayBuffer) {
  if (error) {
    // handle error
    return
  }

  // here's your `arrayBuffer`
})

Usi ng ES6 Promise,如果愿意,可以将其转换为返回Promise:

Using ES6 promises, you could convert this to return a promise if you'd prefer:

function getJpegBytes(canvas) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()

    fileReader.addEventListener('loadend', function () {
      if (this.error) {
        reject(this.error)
      } else {
        resolve(this.result)
      }
    })

    canvas.toBlob(blob => fileReader.readAsArrayBuffer(blob), 'image/jpeg')
  })
}

并这样称呼它:

getJpegBytes(document.querySelector('canvas'))
  .then(arrayBuffer => {
    // here's your `arrayBuffer` if success
  }, error => {
    // handle error
  })

这篇关于从javascript中的画布中保存jpeg字节数组,而无需执行base64步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 07:35