3

I have a web service that takes a base 64 encoded string representing an image, creates a thumbnail of that image using the imagemagick library, then stores both of them in mongodb. I am doing this with the following code (approximately):

var buf = new Buffer(req.body.data, "base64"); //original image

im.resize({ srcData: buf, width: 256 }, function(err, stdout, stderr) {
    this.thumbnail = new Buffer(stdout, "binary");
    //store buf and stdout in mongo
});

You will notice that I am creating a Buffer object using the "binary" encoding, which the docs say not to do:

'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.

First off I'm not sure what they are saying there. I'm trying to create a Buffer object and they seem to imply I should already have one.

Secondly, the source of the problem appears to be that the imagemagick resize method returns a string containing binary data. Doing typedef(stdout) return "string" and printing it out to the screen certainly appears to show a bunch of non-character data.

So what do I do here? I can't change how imagemagick works. Is there another way of doing what I'm trying to do?

2 Answers 2

3

Thats how I am doing the same with success, storing images in mongodb.

//original ---> base64
var thumbnail = new Buffer(req.body.data).toString('base64');
//you can store this string value in a mongoose model property, and save to mongodb

//base64 ---> image
var buffer = new Buffer(thumbnail, "base64");

I am not sure if storing images as base64 is the best way to do it

Sign up to request clarification or add additional context in comments.

2 Comments

In my case storying them as base64 strings still won't work because the imagemagick library doesn't return them that way. It appears to be a string that actually contains non-character bytes. I guess, I'm not really sure. I think I'll contain the owners of that library and ask them what's going on.
Hummmm... but, did you even try the approach I suggested? I guess image magick should return it as binary data, right? In this case it is still valid to convert this binary data to its base64 representation, and when retrieving convert from base64.
0

Please try this as your base64 might not be pre-handled:

var imgRawData =
    req.body.images[0].replace(/^data:image\/png;base64,|^data:image\/jpeg;base64,|^data:image\/jpg;base64,|^data:image\/bmp;base64,/, "");

var yourBuffer = new Buffer(imgRawData, "base64");

Then, save the yourBuffer into MongoDB buffer.

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.