0

I have base64 image format from the backend and i want it to display in the front end using img tag

here's code

router.get('/image_front/:id', function(req, res){
Delivery.findById(req.params.id, function(err, x){
    if(err){
        res.send({'error': err})
    }else{
        let v = 'data:image/png;base64'+', '+ new Buffer.from(x.image_front.data).toString('base64')
        res.send(v)
    }
})
})

for the front end

<img id="sample" src="/image_front/<%=x._id%>" />

when the image source activated the link return the data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAKQAAA.. which working when i copy and paste the image into w3schools to check the data is not corrupted. and it seems the data is work but it won't display using image tag. i don't know what is wrong.

  • Does this answer your question? [How to display Base64 images in HTML?](https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html) – Shijil Narayanan May 25 '20 at 04:55
  • Depending on your environment the image could have been blocked by CSP. You many need to add `img-src data:;` https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP – Kubwimana Adrien May 25 '20 at 05:08

2 Answers2

1

The base64 string encoding is only required if you are embedding the image data in the html.

For delivering the image to a client directly, return the data with the correct content type.

router.get('/image_front/:id', function(req, res){
    Delivery.findById(req.params.id, function(err, x){
        if(err){
            res.send({'error': err})
        } else {
            res.type('png')
            res.send(x.image_front.data)
        }
    })
})
Matt
  • 68,711
  • 7
  • 155
  • 158
1

Base64 encoding isn't what you want here at all. Simply return the image itself.

res.set('Content-Type', 'image/png');
res.end(x.image_front.data);
Brad
  • 159,648
  • 54
  • 349
  • 530