用python实现视频压缩
市面上的视频压缩软件大多需要付费,或是免费试用几次,或是文件大于多少M就得充会员。令人苦恼。用下面的方法,学会用python压缩视频,一劳永逸,还可以以后装个杯😏😏😏
- 首先需要下载这个叫:ffmpeg的工具,下载下来是个压缩包,下载完成之后解压到你的电脑上即可。( 链接:https://pan.baidu.com/s/1GZu7BnxdUJI6SHNhCtmKtg
提取码:mjjf
大家可以从我的百度网盘里下载。这是64位的哦) - 用你写代码的地方输入以下代码
import sys
import os
import zlib
import threading
import platform
from PIL import Image
class Compress_Pic_or_Video(object):
def __init__(self,filePath,inputName,outName=""):
self.filePath = filePath #文件地址
self.inputName = inputName #输入的文件名字
self.outName = outName #输出的文件名字
self.system_ = platform.platform().split("-",1)[0]
if self.system_ == "Windows":
self.filePath = (self.filePath + "\\") if self.filePath.rsplit("\\",1)[-1] else self.filePath
elif self.system_ == "Linux":
self.filePath = (self.filePath + "/") if self.filePath.rsplit("/",1)[-1] else self.filePath
self.fileInputPath = self.filePath + inputName
self.fileOutPath = self.filePath + outName
@property
def is_video(self):
videoSuffixSet = {"WMV","ASF","ASX","RM","RMVB","MP4","3GP","MOV","M4V","AVI","DAT","MKV","FIV","VOB"}
suffix = self.fileInputPath.rsplit(".",1)[-1].upper()
if suffix in videoSuffixSet:
return True
else:
return False
def SaveVideo(self):
fpsize = os.path.getsize(self.fileInputPath) / 1024
if fpsize >= 150.0: #大于150KB的视频需要压缩
if self.outName:
compress = "ffmpeg -i {} -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline -crf 23 -acodec aac -b:a 32k -strict -5 {}".format(self.fileInputPath,self.fileOutPath)
isRun = os.system(compress)
else:
compress = "ffmpeg -i {} -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline -crf 23 -acodec aac -b:a 32k -strict -5 {}".format(self.fileInputPath, self.fileInputPath)
isRun = os.system(compress)
if isRun != 0:
return (isRun,"没有安装ffmpeg")
return True
else:
return True
def Compress_Video(self):
# 异步保存打开下面的代码,注释同步保存的代码
thr = threading.Thread(target=self.SaveVideo)
thr.start()
#下面为同步代码
# fpsize = os.path.getsize(self.fileInputPath) / 1024
# if fpsize >= 150.0: # 大于150KB的视频需要压缩
# compress = "ffmpeg -i {} -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline -crf 23 -acodec aac -b:a 32k -strict -5 {}".format(
# self.fileInputPath, self.fileOutPath)
# isRun = os.system(compress)
# if isRun != 0:
# return (isRun, "没有安装ffmpeg")
# return True
# else:
# return True
if __name__ == "__main__":
b = sys.argv[1:] #测试压缩
savevideo = Compress_Pic_or_Video(b[0],b[1],b[2])
print(savevideo.Compress_Video())
并保存。然后在你的. py文件目录下,shift+鼠标右键点击在此处打开powershell窗口(我保存在了桌面)。如图:
3. 点开输入如图
其中
shipinyasuo.py是你保存的python文件名
D:\桌面 是你要压缩视频的绝对路径(我放在了桌面)
1.mp4 是你压缩视频的文件名(我要压缩的文件名就是1.mp4);
2.mp4 是压缩后的文件,要和压缩后的文件在同一目录下。
完成以后按下回车就开始压缩了,如图
4. 看下我的成果
可以看出压缩了很多,而且效果很好,只是流畅度受到了一点小小的影响。
如果你喜欢就点个赞👍呗!!
关注我带你领略更多python功能!!