0

I am in React hooks trying to utilise code in this question Stackoverflow question- but, as I think someone is pointing out, there are problems implementing this in a local environment.

I have a variable containing my src path:

import avatar from '../../Assets/Photos/avatar.png'

Then I try to set the photo as a useState state:

 const [ photo, setPhoto ] = useState(avatar)

Then I use useEffect to wait until the variable has loaded:

useEffect(() => {
    if (photo) {
        console.log("PHOTO EXISTS!!!!!!!!!!!!!!", photo)
        console.log(convertImgToBase64())

    }
}, [photo])

And the convertImgToBase64 function is almost identical to the one in the question I referenced:

    function convertImgToBase64()
{
    var canvas = document.createElement('CANVAS');
    let img = document.createElement('avatar');
    img.src = photo;
    img.onload = function()
    {
        canvas.height = img.height;
        canvas.width = img.width;
        var dataURL = canvas.toDataURL('image/png');

        canvas = null;
        return dataURL
    };
}

This returns undefined - why is this please?

Davtho1983
  • 3,827
  • 8
  • 54
  • 105

1 Answers1

0

Create an image state:

const[image, setImage] = useState("")

Function to convert to base64:

const convertBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);

      fileReader.onload = () => {
        resolve(fileReader.result);
      };

      fileReader.onerror = (error) => {
        reject(error);
      };
    });
};

Set your image state to base64 string image:

const handleFileRead = async (event) => {
    const file = event.target.files[0];
    const base64 = await convertBase64(file);
    setImage(base64);
};

<input type="file"  multiple accept="image/gif, image/jpeg, image/png" onChange={(e) => handleFileRead(e)} />
Aaron Meese
  • 1,670
  • 3
  • 22
  • 32