使用Node JS将多个JPG加载到动画GIF中

时间:2017-03-14 23:09:22

标签: javascript node.js encoding stream animated-gif

我正在尝试将5个特定的JPG文件名传输到动画GIF中。我查看了几个库并找到了Gif-Encoder。我对溪流不太了解。我似乎无法弄清楚如何将JPEG Decoder的RGB结果传输到编码器的addFrame()方法中。

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();
}

1 个答案:

答案 0 :(得分:2)

是否必须使用读取流?我使用模块' 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);