node ffmpeg fluent-ffmpeg 图片与gif 混合

61 阅读1分钟
const ffmpeg = require('fluent-ffmpeg');
const path = require('path')
function addGifOverlayToImage(imagePath, gifPath, outputPath) {
    ffmpeg()
        .input(imagePath)
        .loop(3) // Duration of the final video, adjust as needed
        .input(gifPath)
        .complexFilter([
            `[0:v][1:v] overlay=10:10:shortest=1` // Overlay GIF on top of the image
        ])
        .outputOptions([
            '-c:v libx264', // Video codec
            '-pix_fmt yuv420p', // Pixel format for broad compatibility
            '-movflags +faststart'
        ])
        .output(outputPath)
        .on('end', () => console.log('Video processing finished successfully.'))
        .on('error', (err) => console.error('Error:', err))
        .run();
}

// Example usage
const imagePath = path.join(__dirname, 'images/image1.jpg'); // Path to your static image
const gifPath = path.join(__dirname, 'images/test.gif'); // Path to your animated GIF
const outputPath = path.join(__dirname,'videos/output_with_gif.mp4'); // Path for the output video file

addGifOverlayToImage(imagePath, gifPath, outputPath);

[0:v][1:v] overlay=10:10:shortest=1命令用于将两个视频流进行叠加。

[0:v]和[1:v]:分别代表第一个和第二个视频输入流。 overlay=10:10:指定叠加的位置,这里是将第二个视频流叠加在第一个视频流的左上角,距离顶部和左侧各10个像素。 shortest=1:表示输出视频的时长以两个输入流中较短的一个为准。