PHP--上传视频并截取封面

时间:2024-02-23 14:39:56

1.首先要安装ffmpeg

 

 2.直接上代码

 1  /**
 2      * 上传视频
 3      * @return mixed
 4      * @author suancai
 5      */
 6     public function upload_video()
 7     {
 8         $files = $_FILES[\'video\'];
 9         if (!$files[\'name\']) {
10             $this->error(\'请选择视频\');
11         }
12         $video = \'\';
13         // if (!$files["error"]) {
14         //判断上传文件类型
15         //  if (($files["type"] == "mp4") {
16         //防止文件名重复
17         $filename = "./uploads/video/" . time() . $files["name"];
18         //检查文件或目录是否存在
19         if (!file_exists($filename)) {
20             $res = move_uploaded_file($files["tmp_name"], $filename);//将临时地址移动到指定地址
21             $fileurl = substr($filename, 1);
22         }
23         //}else{
24         // $this->error(\'视频类型错误\',$files["name"]);
25         // }
26         $server = ($this->auth->isHTTPS() ? \'https://\' : \'http://\') . $_SERVER[\'HTTP_HOST\'];
27         $url = substr($fileurl, 1);
28         $end[\'videoUrl\'] = $url;
29         $end[\'videoImg\'] = $this->getCoverImages($end[\'videoUrl\'], $server);
30         $this->success(\'上传成功\', $end);
31         // }
32     }
33      function getCoverImages($fileUrl, $server)
34     {
35         $result = array();
36         if (!empty($fileUrl)) {
37             $filePath = str_replace($server, "", $fileUrl);
38             if (is_file($filePath)) {
39                 $result = $this->execCommandLine($filePath, $server);
40             }
41         }
42         return $result;
43     }
44 
45     function execCommandLine($file, $server)
46     {
47         $result = array();
48         $pathParts = pathinfo($file);
49         $filename = $pathParts[\'dirname\'] . "/" . $pathParts[\'filename\'];
50         $times = 2;51         $destFilePath = $filename . ".jpg";
52         $command = "/usr/bin/ffmpeg -i {$file} -y -f image2 -ss {$times} -vframes 1 -s 640x360 {$destFilePath}";
53         exec($command);
54         $destUrlPath = str_replace("./uploads/video/", $server, $destFilePath);
55         return $destFilePath;
56     }