Home > Web Front-end > JS Tutorial > body text

How to Convert Base64 to an Image in JavaScript?

DDD
Release: 2024-10-31 03:52:30
Original
996 people have browsed it

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>
Copy after login

Setting the Image's Source

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

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!