-2

I am loading an image in React from a URL external to my app:

 <img id={selectedImage.id} src={selectedImage.url} \>

Now I want the user to be able to press a button and the app should store the image content as base64 data in some variable.

Is there any way for me to reference this specific <img> in React and convert the image content into its base64 text representation?

I have seen various solutions on Stack Overflow. Some of these solutions attempt to retrieve the image from a URL again (which caused CORS issues in my case and also represents redundant loading). E.g. I have looked here: Convert image from url to Base64

If I wanted to implement this solution I would not know how to do so in a React environment:

  1. I don't know how this document.getElementById("imageid") works in a React environment; and
  2. I would also not know where to place the function in React that is supposed to draw a canvas.
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
pascal
  • 365
  • 1
  • 3
  • 16
  • 2
    I believe you can create a `ref` that will act the same as `document.getElementByID()`, it will give you a reference to the dom element : https://reactjs.org/docs/refs-and-the-dom.html – Kokodoko Feb 11 '23 at 17:13
  • Sorry, @jonrsharpe, looks like you had to edit a lot. – pascal Feb 11 '23 at 17:20

1 Answers1

2

you can use ref and when image load call getBas64Image method and pass img tag to it

import { useEffect, useRef } from "react";

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL.replace(/^data:image\/?[A-z]*;base64,/);
  }
  
  //var base64 = getBase64Image(document.getElementById("imageid"));

  //method 1: use ref
  export function Img({imageSource}){
    const imageRef = useRef();
    imageRef.current.onload = ()=>getBase64Image(imageRef.current);
    // imageRef.current is same of document.getElementById

    return <img ref={imageRef} src={imageSource} />
  }
Abbas Bagheri
  • 790
  • 5
  • 10