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

◇◆丶佛笑我妖孽 提交于 2019-12-24 09:00:20

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/42798219/pipe-multiple-jpgs-into-an-animated-gif-using-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!