Categories
JavaScript Answers

How to set image source with base64 with JavaScript?

Spread the love

Sometimes, we want to set image source with base64 with JavaScript.

In this article, we’ll look at how to set image source with base64 with JavaScript.

How to set image source with base64 with JavaScript?

To set image source with base64 with JavaScript, we can set the src property to a base64 URL string.

For instance, we write

document.getElementById("img").src =
  "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";

to select the img element with getElementById.

Then we set its src property to the base64 image URL string to set the src attribute of the img element to that value.

Conclusion

To set image source with base64 with JavaScript, we can set the src property to a base64 URL string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *