运行环境
Win10(1909)(x64)
PHPstudy_pro(小皮)
PHP 5.6
Python 3.10(x64)
PHP代码
// 转换文件名
function to_filename($path)
{
if (IS_WIN) {
// utf8转换为gbk
$path = iconv("UTF-8", "GBK", $path);
}
return $path;
}
// 视频转换为gif
public function video2gif()
{
// Python脚本路径
$py_path = realpath("./video2gif.py");
$py_path = addslashes($py_path);
// dump($py_path);
if (
empty($py_path) ||
!file_exists($py_path)
) {
echo "脚本文件不存在";
die;
}
// 视频路径
$video_path = realpath("./Uploads/202205/6291c3f79ebf8.mp4");
$video_path = realpath("./WeChat_20220601141927.mp4");
$video_path = addslashes($video_path);
// dump($video_path);
if (
empty($video_path) ||
!file_exists($video_path)
) {
echo "视频不存在";
die;
}
// gif路径
$gif_path = getcwd() . DIRECTORY_SEPARATOR . "test_gif";
mkdir($gif_path);
// gif文件名
$gif_name = "abc.gif";
$gif_name = "abc2.gif";
$gif_name = "abc3.gif";
$gif_name = time() . ".gif";
$gif_name = $this->to_filename($gif_name);
$gif_path .= DIRECTORY_SEPARATOR . $gif_name;
$gif_path = addslashes($gif_path);
// dump($gif_path);
dump($gif_name);
// 执行Python脚本
exec("python {$py_path} {$video_path} {$gif_path} {$gif_name} --user 2>&1", $output, $return_val);
dump("python {$py_path} {$video_path} {$gif_path} {$gif_name} --user 2>&1");
dump($output);
dump($return_val);
}
Python
菜鸡用Python做的第一个功能,有点糟糕
一个1m的视频转换出来一个11m gif图片
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import sys
import platform
import subprocess
from http.client import CONFLICT
from moviepy.editor import VideoFileClip
# from moviepy.editor import *
# def open_fp(fp: str):
# """
# 打开文件或文件夹
# 优点: 代码输入参数少, 复制粘贴即可使用, 支持在mac和win上使用, 打开速度快稳定;
# :param fp: 需要打开的文件或文件夹路径
# """
# systemType: str = platform.platform() # 获取系统类型
# if "mac" in systemType: # 判断以下当前系统类型
# # mac系统下,遇到`\\`让路径打不开,不清楚为什么哈,觉得没必要的话自己可以删掉啦,18行那条也是
# fp: str = fp.replace("\\", "/")
# subprocess.call(["open", fp])
# else:
# fp: str = fp.replace("/", "\\") # win系统下,有时`/`让路径打不开
# os.startfile(fp)
def video2gif(video_path, gif_path, gif_name):
vedioClip = VideoFileClip(video_path, audio=False)
duration = vedioClip.duration
CONST_END_TIME = vedioClip.duration
CONST_START_TIME = 0
# open_fp(gif_path)
clip = (vedioClip.subclip(CONST_START_TIME, CONST_END_TIME)
.resize(0.3))
clip.write_gif(gif_path, fps=10)
# clip.write_gif(gif_name, fps=10)
# clip.write_gif(gif_path+"\\"+str(gif_name), fps=10)
# print(gif_path+"\\"+str(gif_name))
video_path = sys.argv[1]
gif_path = sys.argv[2]
gif_name = sys.argv[3]
# video_path = "D:\\phpstudy_pro\\WWW\\jzmall.cc\\Uploads\\202205\\6291c3f79ebf8.mp4"
# gif_path = "D:\\phpstudy_pro\\WWW\\jzmall.cc\\gif_path\\测试.gif"
# gif_name = "D:\\phpstudy_pro\\WWW\\jzmall.cc\\gif_path\\测试.gif"
print(video_path)
print(gif_path)
print(gif_name)
# if not os.path.exists(gif_path):
# os.mkdir(gif_path)
video2gif(video_path, gif_path, gif_name)
print(1)