简体   繁体   English

如何获取图像作为数据 URL,没有 canvas API 或文件阅读器 ZDB974238714CA8ACEFFZ34

[英]How to get an image as a data URL, without the canvas API or the filereader API

There are many questions and answers on SO about how to get an image as a data URL, and well, a lot of them use either the canvas API or the FileReader API. There are many questions and answers on SO about how to get an image as a data URL, and well, a lot of them use either the canvas API or the FileReader API. Using those APIs for such a simple task is a bit heavy handed, so I've decided to do a QnA post about how it can be done in a much simpler manner.将这些 API 用于如此简单的任务有点繁琐,所以我决定写一篇 QnA 帖子,介绍如何以更简单的方式完成它。

Here is a simple function that fetches an image from a provided url, and then outputs said image as a data URL.这是一个简单的 function,它从提供的 url 中获取图像,然后将所述图像作为数据 URL 输出。

async function asDataUrl(src) {
   const req = await fetch(src);
   const res = await req.arrayBuffer();

   const u8Buf = new Uint8Array(res);
   let latinBuf: string = '';
   u8Buf.forEach((byte: number): void =>
      { latinBuf += String.fromCharCode(byte); });

   return `data:${req.headers['content-type']};base64,${btoa(latinBuf)}`;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM