How To Convert Image In Base64

— In this article, we will learn how to convert image in base64.

–First of all, we have to create an application in react.

–Now open your app.js file.

— Then add input element with type file and onchange event.

   
<input type="file" onChange={ImageHandler} />

–Then create an onchange event and add a usestate in your app.js file.

const [image, setImage] = useState()

 const ImageHandler = async (e) => {
        const file = e.target.files[0]
        const base64 = await convertToBase64(file)
        setImage(base64)
 }

–Now write the code for converting the image in base64.

const convertToBase64 = (file) => {  //selected image
       return new Promise((resolve, reject) => {
           const fileReader = new FileReader()
           fileReader.readAsDataURL(file)
           fileReader.onload = () => {
               resolve(fileReader.result)
           }
           fileReader.onerror = (error) => {
               reject(error)
           }
       })
  }

— app.js file:

import React, { useState } from 'react'
function BaseImage() {

    const [image, setImage] = useState()
    const convertToBase64 = (file) => {  //selected image
        return new Promise((resolve, reject) => {
            const fileReader = new FileReader()
            fileReader.readAsDataURL(file)
            fileReader.onload = () => {
                resolve(fileReader.result)
            }
            fileReader.onerror = (error) => {
                reject(error)
            }
        })
    }
    const ImageHandler = async (e) => {
        const file = e.target.files[0]
        const base64 = await convertToBase64(file)
        setImage(base64)
    }
    return (
        <>
            <input type="file" onChange={ImageHandler} />
            <h5>{image}</h5>
        </>
    )
}

export default BaseImage

output:

Submit a Comment

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

Subscribe

Select Categories