Search code examples
meteorgraphicsmagickcollectionfs

CollectionFS: insert image generated server-side


How do I generate a new image on the server and insert it into a collection [using Meteor/CollectionFS + GridFS]?

The wiki explains how to insert from a stream on the server

var readStream = spawn('ls', []).stdout;
var newFile = new FS.File();
newFile.attachData(readStream, {type: 'text/plain'});
newFile.name('ls_result.txt');
Files.insert(newFile);

... but how do I create a readstream for type [image/png]?

---------------------------{edit}---------------------------

I tried this:

var fs = Npm.require('fs');
var writeStream = fs.createWriteStream( 'test.png' );
gm(200, 200, '#000F')
    .setFormat('png')
    .fill('black')
    .drawCircle( 10, 10, 190, 190 )
    .stream('png')
    .pipe(writeStream);
var readStream = fs.createReadStream( 'test.png' );
// ...insert as above

... which creates the file test.png but it has no data ( 0 bytes ). Thus, the insert fails with the unknown filesize error.

---------------------------{edit 2.0}---------------------------

Tried the following which feels like the solution I need ... but it fails in a similar manner:

gm(200, 200, '#000F')
    .setFormat('png')
    .fill('black')
    .drawCircle( 50, 50, 60, 60 )
    .toBuffer( 'PNG', Meteor.bindEnvironment( function( error, buffer )
    {
        if( error ) throw error;

        var file = new FS.File();
        file.attachData( buffer, {type: 'image/png'}, function( err )
        {
            if( err ) throw err;
            file.name( 'test.png' );
            Collections.Builds.insert( file );
        });
    })
);

This throws the error:

I20150520-16:29:10.379(-5)? Exception in callback of async function: Error: Stream yields empty buffer

I20150520-16:29:10.379(-5)? at Socket. (/Users/andrew/.meteor/packages/cfs_graphicsmagick/.0.0.18.rl55ru++os+web.browser+web.cordova/npm/node_modules/gm/lib/command.js:65:17)

I20150520-16:29:10.379(-5)? at Socket.emit (events.js:117:20)

I20150520-16:29:10.379(-5)? at _stream_readable.js:944:16

I20150520-16:29:10.379(-5)? at process._tickCallback (node.js:442:13)

...which seems to suggest the problem is with graphicsmagick.


Solution

  • Solved with help from @andrew-lavers response to this question

    gm(200, 200, '#000F')
        .setFormat('png')
        .fill('black')
        .drawCircle( 50, 50, 60, 60 )
        .toBuffer( Meteor.bindEnvironment( function( error, buffer )
        {
            if( error ) throw error;
    
            var file = new FS.File();
            file.attachData( buffer, {type: 'image/png'}, function( err )
            {
                if( err ) throw err;
                file.name( 'test.png' );
                Collections.Builds.insert( file );
            });
        })
    );
    

    As you can see, I was very close ... just needed to remove the first parameter from the gm.toBuffer method.