Home > Software design >  using Base64 images in react.js
using Base64 images in react.js

Time:03-01

I am trying to use Base64 encoded images in my react app.

currently I load images from a folder and looks something like this:

<img className="..." src={imageFile}></img>

I want to use base64 encoded images, I think I can do this:

<img className="..." src={"data:image/svg xml;base64,PHN2ZyB4bWxucz0iaH...."}></img>

the problem is that the base64 strings are huge, and for some reason I cant store them in my component. I tried putting them in a txt file and doing:

fs.readFile('image.txt', function(err, data){console.log(data);})

but I get tons of errors, including:

Uncaught TypeError: fs.readFile is not a function

among others.

any ideas how to store base64 strings in a separate file and load them into my component?

Thanks!

CodePudding user response:

Decode the base64 using Buffer

let [imgSrc,setImgSrc] = useState('')
// 
let base64_to_imgsrc = Buffer.from(base64String, "base64").toString()
//add the string to the state
setImgSrc(base64_to_imgsrc)

and use it like this

  <img src={"data:image/jpeg;base64,"   imgSrc} />

CodePudding user response:

You can use a variable to store base64 data and export it.

// filename.js
const image = "data:image/svg xml;base64,PHN2ZyB4bWxucz0iaH....";

export default image;

// import
import image from 'filename';

CodePudding user response:

There is three-way to do that, with FileReader and with fetch and the simplest way is to import it.

With Import

import Base64JSON from "./readme.json";

console.log(Base64JSON);

With FileReader

const readFile = async (json) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    const blob = new Blob([JSON.stringify(json)]);

    reader.onload = async (e) => resolve(JSON.parse(e.target.result));
    reader.readAsText(blob);
  });

With Fetch

const readFileUsingHttp = async (path) => {
  const json = await fetch(path);
  return json.json();
};

Here is the sandbox URL that shows all techniques.

Codesandbox: https://codesandbox.io/s/eager-golick-uvtcnh?file=/src/App.js

  • Related