Home  >  Article  >  Web Front-end  >  How to Convert Base64 to an Image in JavaScript?

How to Convert Base64 to an Image in JavaScript?

DDD
DDDOriginal
2024-10-31 03:52:301001browse

How to Convert Base64 to an Image in JavaScript?

Converting Base64 to Image in JavaScript

In your code, item_image holds the base64-encoded image data. To convert this data to an image, follow these steps:

Creating an Image Object

<code class="javascript">var image = new Image();</code>

Setting the Image's Source

<code class="javascript">image.src = 'data:image/png;base64,' + item_image;</code>

This line sets the src property of the image object to the base64-encoded data, including the necessary header indicating the image's data type (data:image/png).

Appending the Image to the DOM

<code class="javascript">document.body.appendChild(image);</code>

This appends the image object to the HTML document, allowing it to be displayed.

Note:

  • The data:image/png;base64 header is crucial for browsers to recognize and render the image correctly.
  • This method converts the base64 data into an in-memory image and displays it dynamically. There is no actual image file created on the client-side.

The above is the detailed content of How to Convert Base64 to an Image in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn