0

So I am using mongoDB as my database and I have saved an image in mongoDB in binary format.

The image below is how the data is being displayed in my database.

enter image description here

I have tried the following:

<img src="data:image/jpeg;base64{<%= user.img.data %>}"/>

But the above code does not seem to work. Please note I am using EJS as a tempting engine.

After doing the inspect element on google chrome I found that the data was being shown like so:

enter image description here

I am not sure how to read this binary image and display it in a img tag in html.

UPDATE:

After making the changes recommended by Alex Matos in the comments I get the following output:

enter image description here

7
  • You are missing a comma after base64 so it should read as: <img src="data:image/bmp;base64,{<%= user.img.data %>}"/> Commented Jan 20, 2016 at 9:41
  • I think you must return your buffer like a string. Something like this var buf2 = new Buffer(user.img.data).toString('base64'); console.log(buf2.toString()); I suppose that you uses nodejs Commented Jan 20, 2016 at 9:43
  • @Kush thank you for the comment. I tried your suggestion but it did not work. Commented Jan 20, 2016 at 9:45
  • @AlexMatos Im gonna try your suggestion now. And yes I'm using node.js Commented Jan 20, 2016 at 9:45
  • Ok, Let me know if it work it. Commented Jan 20, 2016 at 9:51

2 Answers 2

1

If you really got the images data and saved it i mongo db, you could render the image in a canvas and append it wherever you need.

// Renders the image data in a canvas off screen
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var data = ctx.putImageData(YOUR_MONGODB_DATA,0,0);

// Initializes a new image from canvas and appends it to the parent you want
var image = new Image();
image.id = "rendered-picture"
image.src = canvas.toDataURL();
document.getElementById('PARENT_ID').appendChild(image);
Sign up to request clarification or add additional context in comments.

Comments

0

Try returning data from your server using base64_encode.

For example:

    <?php
        $picture = base64_encode(user.img.data);
       <img src="data:image/jpeg;base64{<%= picture %>}"/>
    ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.