Search code examples
node.jsgraphicsmagick

graphicsmagick fails to get size when using gm(buffer,file)


I'm using the node module gm, and I'm trying to identify the size of a PNG image. I've made the following small program to illustrate my issue. The size is retrieved if you use the gm constructor function that takes a file name. It fails if you pass a buffer + file name hint.

The error returned is:

can't buffer image and identify size { [Error: Command failed: gm identify: No decode delegate for this image format ().
gm identify: Request did not return an image.
] code: 1, signal: null }

Code sample:

var fs = require('fs');
var gm = require('gm');

var buffer = fs.readFileSync('./test/test_image.png',{encoding:'binary'});

gm('./test/test_image.png').size(function(err,size) {
    if (err) console.log("can't identify from disk read");
    else {
        gm(buffer,'test_image.png').size(function(err,size) {
            if (err) console.log("can't buffer image and identify size");
            else console.log("all good");
            process.exit(0);
        }); 
    }   
});

Any ideas on how to workaround this? My real use case is getting image data as base64 encoded from web POST endpoint, so reading from disk isn't really an option.


Solution

  • I found the answer, it was RTFM: http://nodejs.org/api/fs.html

    fs.readFileSync(filename, [options])# Synchronous version of fs.readFile. Returns the contents of the filename.

    If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.

    My code was setting the encoding to 'binary' which returns a string, not a buffer.