0

I need to make two resized images from another one.

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

var worker = function(filename) {
    img = gm(fs.createReadStream(filename));
    img.flip();

    this.run = function() {
        async.series([
            function(callback) {
                img.resize(640, 480);
                img.toBuffer(function(err, buffer) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    callback(null, true);
                })
            },
            function(callback) {
                img.resize(320, 240);
                img.toBuffer(function(err, buffer) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    callback(null, true);
                })
            },
        ],
        function(err, results) {
            console.log(err, results);
        });
    };
}

new worker('test.jpg').run();

This code generates error:

Error: gm().stream() or gm().write() with a non-readable stream.

If I replace fs.createReadStream with a filename than everything works just fine. It looks like gm doesn't store the source image from stream in it's internal buffer. Is it a bug or I should know something else about using it in proper way?

Notice: Async is used because in real project I need both results to perform other actions with them.

Lisio
  • 1,571
  • 2
  • 15
  • 22
  • So why are you using a stream then? – robertklep Jun 29 '13 at 19:29
  • I'm already not using it, but it requires to think about copying data from stream into buffer, making code bigger. Anyway, if gm library allows writing gm(stream).resize(...).stream(callback).resize(...).stream(callback) than it should work with streams and files in similar way without workarounds. – Lisio Jun 30 '13 at 22:11

1 Answers1

0

try this, i dont think you need to use writeStreams in this case:

gm(imagePath)
  .resize(640, 480)
  .autoOrient()
  .flip()
  .write(newImagePath, function(e) {
  if (e) throw e;
  gm(newImagePath)
    .resize(320, 240)
    .write(newImagePathSmall, function(e) {
    if (e) throw e;
    console.log('resized successfuly');
  });
});