Graphicsmagick for node does not write all jpg

I use https://github.com/aheckmann/gm to resize the 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 does not record the entire image.

half camel

+3
graphicsmagick
source share
4 answers

I solved this 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 combine them. You can find more information by looking at the source code for the concat bufferjs method: https://github.com/coolaj86/node-bufferjs/blob/master/bufferjs/concat.js

+7
source share

Why don't you just write directly to the output stream when receiving data?

 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' }); stdout.pipe(writeStream); }); 
+3
source share

Just do the following:

 var gm = require('gm').subClass({imageMagick: true}); gm( 'kittens.jpg' ) .resize(50,50) .write( "kittens-small.jpg", function (err) { if( err ) throw err; }); 
+3
source share

I found imagemagick very useful and simple. I also tried graphicsmagick but no luck.

You can install imagemagick with the following command.

 npm install imagemagick 

The following is sample code and documentation for imagemagick at https://github.com/rsms/node-imagemagick :

 var im = require('imagemagick'); im.resize({ srcPath: 'kittens.jpg', dstPath: 'kittens-small.jpg', width: 50, height: 50 }, function(err, stdout, stderr){ if (err) throw err; console.log('resized kittens.jpg to fit within 256x256px'); }); 
+2
source share

All Articles