Search code examples
node.jsgraphicsmagick

How do I create a new image with [node] graphicsmagick using toBuffer


I'm trying to create a new image which will eventually be insert into a mongo database via gridfs. I'd prefer to avoid writing anything to the filesystem so the best route seems to create a new image, write the result to a buffer, then insert the buffer into the database. Unfortunately, the toBuffer method doesn't work for new images:

var gm = require( 'gm' );
gm(200, 200, '#000F')
    .setFormat('png')
    .fill('black')
    .drawCircle( 50, 50, 60, 60 )
    .toBuffer( 'PNG', function( error, buffer )
    {
        if( error ) { console.log( error ); return; }
        console.log( 'success: ' + buffer.length );
    }
);

... yeilds the following error:

[Error: Stream yields empty buffer]


Solution

  • It looks like gm simply doesn't like the 'PNG' argument you're giving to toBuffer. I don't think its necessary either since you've already specified the format as png earlier on. Try simply removing it:

    var gm = require( 'gm' );
    gm(200, 200, '#000F')
        .setFormat('png')
        .fill('black')
        .drawCircle( 50, 50, 60, 60 )
        .toBuffer(function( error, buffer )
        {
            if( error ) { console.log( error ); return; }
            console.log( 'success: ' + buffer.length );
        }
    );