Jimp: Promise based write/getBuffer

Created on 31 Jan 2016  路  14Comments  路  Source: oliver-moran/jimp

Currently, write needs callback.
I'd like to be able to do this:

image.getBuffer(Jimp.MIME_JPEG).then(function(buffer) {
  res.writeHead(200, {
     'Content-Type': Jimp.MIME_JPEG,
     'Content-Length': buffer.length
   });
   res.end(buffer);
})

Most helpful comment

As a workaround for the time being, using Bluebird promisify:

const bluebird = require('bluebird');
const jimp = require('jimp');
jimp.prototype.getBufferAsync = bluebird.promisify( jimp.prototype.getBuffer );

All 14 comments

+1

It's a little bit awkward because methods, write and getBuffer, are currently designed for chaining, like this:

image.scale(0.5).write("image-small.jpg").greyscale()..write("image-small-greyscale.jpg");

@oliver-moran node-horseman has a good chaining strategy. It use bluebird as Promise implementation.

You can continue using callbacks through the bluebird .asCallback.

@efernandesng, thanks and apologies for delay getting back. I'll look into this for the release after next.

Any progress on this?

I'd love native Promises for all jimp methods. Bluebird should not be included by default, it could be used opt-in. Chaning the API requires the test https://github.com/oliver-moran/jimp/issues/227 to be implemented first

Any progress on this?

As a workaround for the time being, using Bluebird promisify:

const bluebird = require('bluebird');
const jimp = require('jimp');
jimp.prototype.getBufferAsync = bluebird.promisify( jimp.prototype.getBuffer );

Node 8, has built in promisify method

const util = require('util');
const jimp = require('jimp');
jimp.prototype.getBufferAsync = util.promisify( jimp.prototype.getBuffer );

For >= ES6, native Promise is available:

(new Promise((resolve, reject) => {
  <img>.getBuffer(<mime>, (error, buf) => {
    return error ? reject(error) : resolve(buf);
  });
})).then((buf) => {
  // Do something with buf
}).catch((error) => {
  // error from getBuffer()
});

Using promisify now results in a "cannot read property 'width' of undefined". Any status on making this a promise?

+1

@FireController1847

import { promisify } from "util";

const jimp = new Jimp(100, 100); // jimp object
const boundGetBuffer = promisify(jimp.getBuffer.bind(jimp));

async function main() {
   const buffer = await boundGetBuffer();
}
main();

see https://mdn.io/bind
see https://nodejs.org/dist/latest/docs/api/util.html#util_util_promisify_original

I had actually been doing it wrong and got it to work lol, thanks anyways

Was this page helpful?
0 / 5 - 0 ratings

Related issues

oliver-moran picture oliver-moran  路  16Comments

fabiusss picture fabiusss  路  14Comments

mkondel picture mkondel  路  14Comments

yangshenhuai picture yangshenhuai  路  16Comments

oliver-moran picture oliver-moran  路  55Comments