如何在React中将来自URL的图像转换为base64。

huangapple go评论78阅读模式
英文:

How to convert Image from Url to base64 in react js

问题

我从Firebase存储获取图像的URL,并希望将这些图像转换为Base64。

英文:

I am getting Url of images from firebase storage and want to convert these images to base64

答案1

得分: 0

尝试一下:
英文:

Give it a go:

var request = require('request').defaults({ encoding: null });

request.get(/* URL FIREBASE */, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        data = Buffer.from(body).toString('base64');
        console.log(data);
    }
});

答案2

得分: 0

客户端 JavaScript 代码。使用FileReader和fetch。

const base64 = await fetch('https://i.imgur.com/gBi0yjr.png')
  .then(response => response.blob())
  .then(blob => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return new Promise((res) => {
      reader.onloadend = () => {
        res(reader.result);
      }
    })
  })
英文:

Client side js. With FileReader and fetch.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const base64 = await fetch(&#39;https://i.imgur.com/gBi0yjr.png&#39;)
  .then(response =&gt; response.blob())
  .then(blob =&gt; {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return new Promise((res) =&gt; {
      reader.onloadend = () =&gt; {
      res(reader.result);
    }})
  })

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月15日 20:38:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定