user712410
user712410

Reputation:

Node.js asynchronous if statements GraphicsMagick

I am trying to use the GraphicsMagick library in my Node.js app, to manipulate images on the fly.

After the image has been selected using:

var image = gm('/path/to/image.jpg');

I want to perform several actions on it. The issue I am facing is because the actions to be performed come from variables. For example, if blur is true, it should blur the image. If scale is also true, the blurred image should then be scaled. The trouble is, GraphicsMagic library is asynchronous, so this script would result in many actions being performed at the same time, which might turn out horribly.

The functions do accept callbacks, as shown on this example on GitHub. Although they appear synchronous, this answer here confirms that they're asynchronous. New answer here shows that the functions are synchronous.

How can I perform the actions on the image one by one, while staying non-blocking, when I don't know which actions are being performed?

I was thinking something along the lines of a NextAction() function which would be executed in the callback. The NextAction() would then trigger the next action, but I'm not sure about how to go about this.

I have researched StratifiedJS, but decided against it as I don't want to further complicate my app, and I don't think my PaaS supports it.

if(blur){
  image = image.blur(blur1, blur2);
}
if(scale){
  image = image.resize(resizeX, resizeY);
}
if(sepia){
  image = image.sepia();
}

Upvotes: 1

Views: 876

Answers (1)

moka
moka

Reputation: 23047

GraphicsMagick will not make any executions and work when you are calling methods on image like: resize, blur etc. an they are very lightweight.

In fact all they do - is adding arguments to the chain (strings to array of arguments). So the object that gm() returns - is chain object, and does not do much until you will performwrite method.

When write method is called it will in fact spawn process that all arguments will be passed to, and this is place where all calculation happens, and that is why it is async.

So in order to make your optional methods - you do exactly the way you need to do it:

if(blur){
  image = image.blur(blur1, blur2);
}
if(scale){
  image = image.resize(resizeX, resizeY);
}
if(sepia){
  image = image.sepia();
}

At the end image will contain array of arguments, and calling write to it, will execute all of them. Every time you call any of those methods which in fact you can have a look here: https://github.com/aheckmann/gm/blob/master/lib/args.js All they do is return new modified object with added arguments.

Here is more details and explanation over this question and how it works: https://stackoverflow.com/a/17745079/1312722

Upvotes: 1

Related Questions