首页 > 解决方案 > 使用 FFMPEG 在视频上叠加图像

问题描述

我正在尝试使用 ffmpeg 和 php 在视频上叠加图像:

$ffmpeg = FFMpeg\FFMpeg::create();
    $video = $ffmpeg->open($videoOriginalFilePath);
    $video
        ->filters()
        ->watermark($imageFilePath, array(
            'position' => 'absolute',
            'x' => 100,
            'y' => 0,
    ));
    $video->save(new FFMpeg\Format\Video\X264(), 'output.mp4');

这种方式工作正常,但问题是我需要这个“$imageFilePath”不是真正的路径,而是由 imagick 创建的图像。无论如何我可以做到吗?

标签: phpffmpegimagick

解决方案


我通过使用以下代码解决了这个问题:

// create temp file
$temp = new SplTempFileObject();

// get its file path
$tempPath = tempnam(sys_get_temp_dir(), $temp);

// open the file
$file = fopen($tempPath, "w");

// write the image to the temp file
$image->setImageFormat('png');
$image->writeImageFile($file);

// overlay the image using the temp file path
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($video);
$video
  ->filters()
  ->watermark($tempPath, array(
  'position' => 'absolute',
    'x' => $xOffset,
    'y' => $yOffset,
  ));

$video->save(new FFMpeg\Format\Video\X264(), 'output.mp4');

推荐阅读