Reputation: 11
I want to add a watermark to a video that changes randomly during processing. I am using Node.js and Express.js with FFmpeg. Currently, I am able to add a static watermark to the video using the drawtext filter. However, I want to change the watermark text randomly every few seconds.
How can I achieve this using FFmpeg in my Node.js and Express.js app? Here's my current code:
const email = '[email protected]';
app.post('/addwatermark', upload.single('video'), (req, res) => {
const fileName = path.basename(req.file.path) + '.mp4';
const outputPath = `public/reduceSize/${fileName}`;
const outputPathWithWatermark = `public/reduceSize/${fileName}-wm.mp4`;
let watermarkPosition = { x: 10, y: 650 };
// Create the directory if it doesn't exist
const outputDir = path.dirname(outputPathWithWatermark);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Send a comment to keep the connection alive
res.write(': ping\n\n');
// Function to randomly generate watermark position
const changeWatermarkPosition = () => {
watermarkPosition = { x: Math.floor(Math.random() * 100), y: Math.floor(Math.random() * 100) };
};
// Change watermark position every 5 seconds
setInterval(changeWatermarkPosition, 5000);
const watermarkStyle = `-vf drawtext=text='${email}':x=(w-text_w-10):y=(h-text_h-10):fontcolor=white:fontsize=24:shadowcolor=black:shadowx=1:shadowy=1:box=1:y=${watermarkPosition.y}:fontcolor=red:fontsize=24:shadowcolor=black:shadowx=1:shadowy=1:box=1:[email protected]`
ffmpeg(req.file.path)
.addOption(watermarkStyle)
.output(outputPathWithWatermark)
.videoCodec('libx264')
.audioCodec('aac')
.size('50%')
.on('error', (err) => {
console.error(`FFmpeg error: ${err.message}`);
res.status(500).json({ message: err.message });
})
.on('progress', (progress) => {
// Set the watermark position every 5 seconds randomly
changeWatermarkPosition();
const mb = progress.targetSize / 1024;
const data = {
message: `Processing: ${mb.toFixed(2)} MB converted`,
watermark: `Adding watermark to video: ${progress.framesProcessed} frames processed`
};
console.log(data.message);
res.write(`data: ${JSON.stringify(data)}\n\n`);
})
.on('end', () => {
console.log(`Video successfully converted to ${outputPathWithWatermark}`);
// Remove the temporary file
})
.run();
});
I want to secure my video from unauthorized person by using email in a video and the email will be move around the video randomly every 5 seconds.
I have read this (Add dynamic watermark that randomly changes position over video React/Node) document but didn't get any solution.
Upvotes: 0
Views: 445