Search code examples
javascriptnode.jsencodingstreamanimated-gif

Pipe multiple JPG's into an animated GIF using Node JS


I am trying to pipe 5 specific JPG file names into an animated GIF. I have looked through several libraries and found Gif-Encoder. I am not very good with streams. I cannot seem to figure out how to pipe the RGB result from the JPEG Decoder into the addFrame() method of the encoder.

function createAnimatedGif(jpgPaths, animatedGifPath) {
    let encoder = new GifEncoder(1280, 720);

    let writeStream = fs.createWriteStream(animatedGifPath);
    encoder.pipe(writeStream);
    encoder.writeHeader();

    jpgPaths.forEach(filePath => {
        fs.createReadStream(filePath)
            .pipe(new JPEGDecoder)
            //.pipe(encoder);
            //.pipe(pixels => encoder.addFrame(pixels));
    });

    encoder.finish();
}

Solution

  • Is using a read streams a must? I had some success using the module 'get-pixels'.

    var getPixels = require('get-pixels')
    var GifEncoder = require('gif-encoder');
    var gif = new GifEncoder(1280, 720);
    var file = require('fs').createWriteStream('img.gif');
    var pics = ['./pics/1.jpg', './pics/2.jpg', './pics/3.jpg'];
    
    gif.pipe(file);
    gif.setQuality(20);
    gif.setDelay(1000);
    gif.writeHeader();
    
    var addToGif = function(images, counter = 0) {
      getPixels(images[counter], function(err, pixels) {
        gif.addFrame(pixels.data);
        gif.read();
        if (counter === images.length - 1) {
          gif.finish();
        } else {
          addToGif(images, ++counter);
        }
      })
    }
    addToGif(pics);