Karthi
Karthi

Reputation: 3489

How to show base64 image in react?

I am storing the image in a base64 format in a node. Then I am receiving it and storing in a variable. and show it in the tag but it is not showing. Correct values are receiving from server. In render, function condition is true if the state is set.even if its true its not showing.

getImage() {
    console.log('getImage');
    axios.get(`http://localhost:4000/image/get`).then((result) => {
        this.setState({ image: result })
        console.log(result);
    });
}

render(){
    {this.state.image ? <img src={this.state.image}></img>: ''}
}

I am getting exact base64 string which i am storing in the server.It returns

<img src="[object Object]">

in DOM.I don't know where am I going wrong

EDIT

router.route('/image/get').get((req, res) => {
    console.log('inside img get');
    Image.find((err, result) => {
        if (err) {
            res.json({ "error": true, "message": "error fetching data" });
        } else {
            // console.log(result);
            res.json(result);
        }
    })

});

model

const mongoose=require('mongoose');
const Schema=mongoose.Schema;
var ImageSchema=new Schema({
    imageName:{
        type:String
    },
    imageData:{
        type:String
    }

});

export default mongoose.model('Image', ImageSchema);

Upvotes: 23

Views: 77793

Answers (6)

Kiril Dobrev
Kiril Dobrev

Reputation: 871

In my case I had to load base64 image from data base to component in react. Img component can read directly the base64 string. Passing the string directly from the function didn't worked for me. Then I added useEffect hook that calls db and sets state with returned value. After that it started working as expected. Code I implemented:

my useState declaration:

const [myBase64string, setBase64string] = useState<string>();

my useEffect hook:

useEffect(() => {

const getStringFunction = async () => {
  const myBase64string = await funcThatGetsBase64imgString();
  setBase64string(myBase64string);
};

getStringFunction();
},[])

Image component in return section:

    return (
<div>
<img
    className="myClassName"
    alt="Some alt name"
    src={`data:image/png;base64,${myBase64string}`}
  />
</div>

Upvotes: 0

Codemaker2015
Codemaker2015

Reputation: 15716

You can't directly append base64 string to image source. First you have to decode it using Buffer then append that data in the src.

Try like this.

decodeBase64(base64data) {
    let base64ToString = Buffer.from(base64data, "base64").toString()
    this.setState({data: base64ToString })
}

render() {
    return (
       <img src={"data:image/jpeg;base64," + this.state.data} />
    )
}

base64data is the data in base64 format.

Upvotes: 2

Divjot Singh
Divjot Singh

Reputation: 21

The answer given by matias bustos works correctly only just that you need to add height and width to the image tag like this:

render(){
   {this.state.image ? 
      <img width='500' height='200' src={`data:image/png;base64,${this.state.image}`}/>: 
   ''}
}

Upvotes: 1

user3266237
user3266237

Reputation: 61

When you get this error:

<img src="[object Object]">

this means you insert an object to the src instead of a string. my guess is that your response returns an object and not string

 axios.get(`http://localhost:4000/image/get`).then((result) => {
        this.setState({ image: result })
        console.log(result);
    });

check if the result is an object

Upvotes: 2

Harshit Agarwal
Harshit Agarwal

Reputation: 2420

const byteCharacters = atob(result);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);

let image = new Blob([byteArray], { type: 'image/jpeg' });

Once you have the Blob you need to convert that into a data url like this:

let imageUrl = URL.createObjectURL(image);
this.setState({image: imageUrl});

now u can use this url saved in your state as a source for image like this:

<img src={this.state.image} />

Hope this helps!!

Upvotes: 4

Mat&#237;as Bustos
Mat&#237;as Bustos

Reputation: 388

Did you make sure to add the encoding type in the src attribute along with the base64 encoded value?

render(){
    {this.state.image ? <img src={`data:image/png;base64,${this.state.image}`}/>: ''}
}

Upvotes: 32

Related Questions