Graphicsmagick for node not writing the whole jpg

Pickels picture Pickels · Apr 28, 2012 · Viewed 8.3k times · Source

I am using https://github.com/aheckmann/gm to resize an image.

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

var input = __dirname   + '/input.jpg';
var output = __dirname + '/output.jpg';

gm(input)
  .resize(350)
  .stream( function(err, stdout, stderr) {

    var writeStream = fs.createWriteStream( output, { encoding: 'base64' } );

    var i = '';

    stdout.on( 'data', function(data){

      i += data.toString('base64');

    });

    stdout.on('end', function(){

      writeStream.write( new Buffer(i, 'base64') );
      writeStream.end();

    });

  } );

The problem is that it's not writing the whole image.

half camel

Answer

Pickels picture Pickels · Apr 28, 2012

I've solved it by using the https://github.com/coolaj86/node-bufferjs concat method.

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

var input = __dirname   + '/input.jpg';
var output = __dirname + '/output.jpg';

require('bufferjs');

gm(input)
  .resize(800)
  .stream( function(err, stdout, stderr) {

    ws = fs.createWriteStream( output );

    i = [];

    stdout.on( 'data', function(data){

      console.log('data');

      i.push( data );


    });

    stdout.on( 'close', function(){

      console.log( 'close' );

      var image = Buffer.concat( i );
      ws.write( image.toString('base64'), 'base64' );
      ws.end();

    });

  } );

Apparently you need to keep track of the length/index of your buffers when you concat them. You can find more info by looking at the source code of bufferjs' concat method: https://github.com/coolaj86/node-bufferjs/blob/master/bufferjs/concat.js