Get image data url in JavaScript?

后端 未结 8 2048
南笙
南笙 2020-11-21 05:11

I have a regular HTML page with some images (just regular HTML tags). I\'d like to get their content, base64 encoded preferably, without the need

8条回答
  •  盖世英雄少女心
    2020-11-21 05:52

    A more modern version of kaiido's answer using fetch would be:

    function toObjectUrl(url) {
      return fetch(url)
          .then((response)=> {
            return response.blob();
          })
          .then(blob=> {
            return URL.createObjectURL(blob);
          });
    }
    

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    Edit: As pointed out in the comments this will return an object url which points to a file in your local system instead of an actual DataURL so depending on your use case this might not be what you need.

    You can look at the following answer to use fetch and an actual dataURL: https://stackoverflow.com/a/50463054/599602

提交回复
热议问题