使用 Deno 的 Oak 包显示 base64 图像

时间:2021-03-18 19:14:56

标签: deno oak

我有一个 base64 编码的图像存储在我的数据库中,所以开始看起来像这样 data:image/png;base64,iVB..,我在我的“图像”端点从数据库返回它。

我当然可以只使用 JavaScript 获取内容并将 base64 字符串包含为 img 源,它会呈现得很好,但我也希望在我转到端点时能够查看图像我的浏览器。我已经尝试了不同标题的组合,但无法正常工作。

如何使用 Oak 渲染 base64 图像?

编辑

这是我最终使用的代码,任何感兴趣的人!

const getImage = async (
  { params, response }: { params: { id: string }; response: Response },
) => {
  // Get the image using the ID from the URL
  const image = await imageDatabase.findOne({ _id: ObjectId(params.id) });

  // If there is no image found
  if (!image) {
    response.status = 404;
    return;
  }

  // Return the image to the user
  const semicolonIndex = image.base64!.indexOf(';')
  const colonIndex = image.base64!.indexOf(':')
  const commaIndex = image.base64!.indexOf(',')

  const imageSize = image.base64!.slice(colonIndex + 1, semicolonIndex);
  const imageData = image.base64!.slice(commaIndex + 1);

  response.headers.set('Content-Type', imageSize)
  response.body = base64.toUint8Array(imageData)
};

1 个答案:

答案 0 :(得分:2)

HTTP 不支持 base64 图像内容。您应该对其进行解码并返回内容类型。

const images: any = {
  beam: 'data:image/png;base64,<base64-string>',
  google: 'data:image/png;base64,<base64-string>',
}

router.get('/image/:id', ctx => {
  if (ctx.params && ctx.params.id && ctx.params.id in images) {
    const image: string = images[ctx.params.id]
    const colonIdx = image.indexOf(':')
    const semicolonIdx = image.indexOf(';')
    const commaIdx = image.indexOf(',')
    // extract image content type
    ctx.response.headers.set('Content-Type', image.slice(colonIdx + 1, semicolonIdx))
    // encode base64
    ctx.response.body = base64.toUint8Array(image.slice(commaIdx + 1))
  }
})

要查找完整代码,请参阅 code on github

或者你可以直接运行我的示例

deno run -A https://raw.githubusercontent.com/XDean/StackOverflow/master/src/main/deno/Q66697683.ts