【问题标题】:How to use binary image in html img tag? [duplicate]如何在 html img 标签中使用二进制图像? [复制]
【发布时间】:2020-12-06 08:54:25
【问题描述】:

我像这样在 mongoDB 中存储图像:

img: {
  contentType: "image/png"
  data: {
    data: Array(135239),
    type: "Buffer"
  }
}

然后我将它们放在前端并尝试在 html img 标签中使用,但没有图片 我试图将数据转换为

let blob = new Blob([img.data], {type : img.contentType})
let img = document.createElement('img').setAttribute('src', URL.createObjectURL(blob))
let container = document.getElementById('container')
container.appendChild(img)

let img = document.createElement('img').setAttribute('src', `data:${img.contentType};base64,${img.data}`)
let container = document.getElementById('container')
container.appendChild(img)

但似乎没有一个不起作用

附:在指南中写了我应该转换 img.data.toString('base64'),但它也不起作用

【问题讨论】:

  • @Sean 只是一个错字,应该是 img.data.data 然后cause if i remove brackets, ill 得到 TypeError: Failed to construction 'Blob': The object must have a callable @@iterator property., 但是反正应该是img.data.data,还是不行
  • @SalmenBejaoui 不幸的是,没有,但我找到了另一个帖子,感谢你的

标签: javascript html mongodb


【解决方案1】:

如果您有同样的问题,只需检查您是否使用本指南: https://www.geeksforgeeks.org/upload-and-retrieve-image-on-mongodb-using-mongoose/ 如果是这样,只需执行与此处相同的操作:

function toBase64(arr) {
   arr = new Uint8Array(arr) if it's an ArrayBuffer
   return btoa(
      arr.reduce((data, byte) => data + String.fromCharCode(byte), '')
   );
}

【讨论】:

猜你喜欢
  • 2017-02-04
  • 1970-01-01
  • 2017-02-04
  • 2021-08-03
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多