Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert image data response to Image base64?

this is my api

https://besticon-demo.herokuapp.com/icon?url=facebook.com&size=80..120..200

when I am testing this in postman I am getting Image..But how I can do with axios. I am getting very long string(like �PNG...) right now with Axios

So how I can use that response to show the image..

   axios.get(RequestURL, { withCredentials: false })
                .then(function (response) {
                    // handle success
                    console.log(response)
                    var b64Response = btoa(response.data) 
                    setImageServer('data:image/png;base64,' + b64Response) // not showing image
                })

Also getting error when try to run btoa

DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

HTML

 <img src={ImageServer}/>
like image 271
sanket kheni Avatar asked May 04 '21 18:05

sanket kheni


People also ask

Can we convert image URL to Base64?

We can convert an image to a base64 URL by loading the image with the given URL into the canvas and then call toDataURL to convert it to base64.

What is Base64 image data?

Base64 encoding is a way to encode binary data in ASCII text. It's primarily used to store or transfer images, audio files, and other media online. It is also often used when there are limitations on the characters that can be used in a filename for various reasons.


1 Answers

axios.get('RequestURL', { responseType: 'arraybuffer' })
.then(response => {
      let blob = new Blob(
        [response.data], 
        { type: response.headers['content-type'] }
      )
      let image = window.URL.createObjectURL(blob)
      return image
    })
axios.get('RequestURL', {responseType: 'blob'})
.then(response => {
  let imageNode = document.getElementById('image');
  let imgUrl = URL.createObjectURL(response.data)
  imageNode.src = imgUrl
})
like image 151
Yang Yu Avatar answered Oct 17 '22 08:10

Yang Yu