PHP使用ffmpeg为视频生成预览图

默认取视频第1秒截图作为预览图

<?php

namespace app\common\library;

//视频获取第一帧做缩略图
class VideoThumb
{

    public $timeStamp = '00:00:01';

    public function createThumb($videoPath)
    {
        $uploadPath = public_path() . '/uploads/';
        $videoPath = $uploadPath . $videoPath;
        if (!is_file($videoPath)) {
            return false;
        }

        if (!$this->isVideoFile($videoPath)) {
            return false;
        }

        $thumbPath = 'videos_thumb/' . $this->autoBuildName() . '.jpg';
        $thumbPathFull = $uploadPath . $thumbPath;

        $dir = dirname($thumbPathFull);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        // FFmpeg命令,-ss表示时间戳,-vframes 1表示只截取一帧,-f image2表示输出图片格式
        $ffmpegCommand = "ffmpeg -ss {$this->timeStamp} -i \"{$videoPath}\" -frames:v 1 \"{$thumbPathFull}\"";

        // 执行FFmpeg命令
        $output = [];
        exec($ffmpegCommand, $output, $returnVar);

        // 检查命令是否成功执行
        return $returnVar == 0 ? $thumbPath : false;
    }

    public function isVideoFile($filePath)
    {
        // 创建一个fileinfo资源
        $finfo = finfo_open(FILEINFO_MIME_TYPE);

        // 获取文件的MIME类型
        $mimeType = finfo_file($finfo, $filePath);

        // 关闭fileinfo资源
        finfo_close($finfo);

        // 定义可能的视频MIME类型
        $videoTypes = [
            'video/mp4',
            'video/avi',
            'video/quicktime',
            'video/x-msvideo',
            'video/x-ms-wmv',
            'video/mpeg',
            'video/ogg',
            'video/webm',
            'video/3gpp',
            'video/3gpp2',
            'video/quicktime',
            'video/x-matroska',
        ];

        // 检查MIME类型是否在视频类型数组中
        return in_array($mimeType, $videoTypes);
    }

    /**
     * 自动生成文件名
     * @access protected
     * @return string
     */
    public function autoBuildName()
    {
        return date('Ymd') . DIRECTORY_SEPARATOR . md5(microtime(true));
    }
}

 

posted @ 2024-12-18 22:06  tros  阅读(116)  评论(0)    收藏  举报