Python视频压缩
阅读原文时间:2023年07月09日阅读:1

html, body { font-family: "SF UI Display", ".PingFang SC", "PingFang SC", "Neue Haas Grotesk Text Pro", "Arial Nova", "Segoe UI", "Microsoft YaHei", "Microsoft JhengHei", "Helvetica Neue", "Source Han Sans SC", "Noto Sans CJK SC", "Source Han Sans CN", "Noto Sans SC", "Source Han Sans TC", "Noto Sans CJK TC", "Hiragino Sans GB", sans-serif; font-size: 16px; min-width: 200px; max-width: 760px; margin: 0 auto; padding: 1rem; line-height: 1.5rem }
h1, h2, h3, h4, h5, h6 { font-family: "PT Sans", "SF UI Display", ".PingFang SC", "PingFang SC", "Neue Haas Grotesk Text Pro", "Arial Nova", "Segoe UI", "Microsoft YaHei", "Microsoft JhengHei", "Helvetica Neue", "Source Han Sans SC", "Noto Sans CJK SC", "Source Han Sans CN", "Noto Sans SC", "Source Han Sans TC", "Noto Sans CJK TC", "Hiragino Sans GB", sans-serif; text-rendering: optimizelegibility; margin-bottom: 1em; font-weight: bold; line-height: 1.8rem }
h1, h2 { position: relative; padding-top: 1rem; padding-bottom: 0.2rem; margin-bottom: 1rem; border-bottom: 1px solid rgba(238, 238, 238, 1) }
h2 { padding-top: 0.8rem; padding-bottom: 0.2rem }
h1 { font-size: 1.6rem }
h2 { font-size: 1.4rem }
h3 { font-size: 1.2rem }
h4 { font-size: 1.1rem }
h5 { font-size: 1rem }
h6 { font-size: 0.9rem }
table { border-collapse: collapse; border-spacing: 0; margin-top: 0.8rem; margin-bottom: 1.4rem }
tr { background-color: rgba(255, 255, 255, 1); border-top: 1px solid rgba(204, 204, 204, 1) }
th, td { padding: 5px 14px; border: 1px solid rgba(221, 221, 221, 1) }
blockquote { font-style: italic; font-size: 1.1em; line-height: 1.5em; padding-left: 1em; border-left: 4px solid rgba(213, 213, 213, 1); margin-left: 0; margin-right: 0; margin-bottom: 1.5rem }
a { color: rgba(24, 99, 161, 1) }
a:hover { color: rgba(27, 67, 141, 1) }
pre, code, p code, li code { font-family: Menlo, Monaco, "Andale Mono", "lucida console", "Courier New", monospace }
pre { -webkit-border-radius: 0.4em; -moz-border-radius: 0.4em; -ms-border-radius: 0.4em; -o-border-radius: 0.4em; border-radius: 0.4em; border: 1px solid rgba(231, 222, 195, 1); line-height: 1.45em; font-size: 0.9rem; margin-bottom: 2.1em; padding: 0.8em 1em; color: rgba(88, 110, 117, 1); overflow: auto; background-color: rgba(253, 246, 227, 1) }
:not(pre)>code { display: inline-block; text-indent: 0; background: rgba(255, 255, 255, 1); font-size: 0.9rem; line-height: 1.5em; color: rgba(85, 85, 85, 1); border: 1px solid rgba(221, 221, 221, 1); -webkit-border-radius: 0.4em; -moz-border-radius: 0.4em; -ms-border-radius: 0.4em; -o-border-radius: 0.4em; border-radius: 0.4em; padding: 0 0.3em; margin: -1px 4px }
pre code { font-size: 1em !important; border: none }
img { max-width: 100%; padding: 8px 0 }
hr { height: 0; margin: 15px 0; overflow: hidden; background: rgba(0, 0, 0, 0); border-top: 0; border-right: 0; border-bottom: 1px solid rgba(221, 221, 221, 1); border-left: 0 }
figcaption { text-align: center }
code[class*="language-"], pre[class*="language-"] { color: rgba(101, 123, 131, 1); font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace; text-align: left; white-space: pre; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; -moz-tab-size: 4; -o-tab-size: 4; tab-size: 4; -webkit-hyphens: none; -moz-hyphens: none; -ms-hyphens: none; hyphens: none }
{ background: rgba(7, 54, 66, 1) }
pre[class*="language-"]::selection, pre[class*="language-"] ::selection, code[class*="language-"]::selection, code[class*="language-"] ::selection { background: rgba(7, 54, 66, 1) }
pre[class*="language-"] { padding: 1em; margin: 0.5em 0; overflow: auto; border-radius: 0.3em }
:not(pre)>code[class*="language-"], pre[class*="language-"] { background-color: rgba(253, 246, 227, 1) }
:not(pre)>code[class*="language-"] { padding: 0.1em; border-radius: 0.3em }
.token.comment, .token.prolog, .token.doctype, .token.cdata { color: rgba(147, 161, 161, 1) }
.token.punctuation { color: rgba(88, 110, 117, 1) }
.namespace { opacity: 0.7 }
.token.property, .token.tag, .token.boolean, .token.number, .token.constant, .token.symbol, .token.deleted { color: rgba(38, 139, 210, 1) }
.token.selector, .token.attr-name, .token.string, .token.char, .token.builtin, .token.url, .token.inserted { color: rgba(42, 161, 152, 1) }
.token.entity { color: rgba(101, 123, 131, 1); background: rgba(238, 232, 213, 1) }
.token.atrule, .token.attr-value, .token.keyword { color: rgba(133, 153, 0, 1) }
.token.function, .token.class-name { color: rgba(181, 137, 0, 1) }
.token.regex, .token.important, .token.variable { color: rgba(203, 75, 22, 1) }
.token.important, .token.bold { font-weight: bold }
.token.italic { font-style: italic }
.token.entity { cursor: help }
pre[class*="language-"].line-numbers { position: relative; padding-left: 3.8em; counter-reset: linenumber 0 }
pre[class*="language-"].line-numbers>code { position: relative; white-space: inherit }
.line-numbers .line-numbers-rows { position: absolute; pointer-events: none; top: 0; font-size: 100%; left: -3.8em; width: 3em; letter-spacing: -1px; border-right: 1px solid rgba(153, 153, 153, 1); -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none }
.line-numbers-rows>span { pointer-events: none; display: block; counter-increment: linenumber 1 }
.line-numbers-rows>span:before { content: counter(linenumber); color: rgba(153, 153, 153, 1); display: block; padding-right: 0.8em; text-align: right }
@media print { code[class*="language-"], pre[class*="language-"] { overflow: visible; word-wrap: break-word !important } }

Python视频压缩

应视频石大的要求,写了一段python代码,来对视频进行压缩,顺便写了一下图片压缩,但发现对.png格式的图片压缩效果不太好,其他的格式都没什么大问题。

先已经支持的格式:

  • 视频:.wmv,.asf,.asx,.rm,.rmvb,.mp4,.3gp,.mov,.m4v,.avi,.dat,.mkv,.fiv,.vob
  • 图片:.bmp,.gif,.jpeg,.jpg,.TIFF,.svg,.pcx,.wmf,.emf,.lic,.eps,.tga

所需要的环境

python3.7 ->python 环境配置 Windows&Mac

ffmpeg -> ffmpeg安装 Windows&Mac


使用方法

  1. 新建一个moriarty.py文件,将文章末尾的代码复制到文件中。

  2. 在python文件的文件夹中进入终端(或cmd)输入指令

    python moriarty.py -address -input. -output.

其中-address 是所需要压缩的视频或文件的所在文件夹的绝对地址

-input.是所需要压缩的视频或图片的名称及格式名。一定要加格式名

-output. 是压缩后的视频或文件的名称和格式名(名称可以自己取)。

  1. 压缩后的文件会出现在同一文件夹中。

代码

#视频压缩
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:
            if self.outName:
                compress = "ffmpeg -i {} -vcodec libx265 -crf 20 {}".format(self.fileInputPath,self.fileOutPath)
                isRun = os.system(compress)
            else:
                compress = "ffmpeg -i {} -vcodec libx265 -crf 20 {}".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()

if __name__ == "__main__":
    tag = sys.argv[1:]
    savevid = Compress_Pic_or_Video(tag[0],tag[1],tag[2])
    print(savevid.Compress_Video())



#压缩图片
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_picture(self):
        picSuffixSet = {"BMP","GIF","JPEG","TIFF","PNG","SVG","PCX","WMF","EMF","LIC","EPS","TGA","JPG"}
        suffix = self.fileInputPath.rsplit(".",1)[-1].upper()
        if suffix in picSuffixSet:
            return True
        else:
            return False

    def SavePic(self):
        fpsize = os.path.getsize(self.fileInputPath) / 1024
        if fpsize >= 50.0:
            im = Image.open(self.fileInputPath)
            imBytes = im.tobytes()
            imBytes = zlib.compress(imBytes, 5)
            im2 = Image.frombytes('RGB', im.size, zlib.decompress(imBytes))
            if self.outName:
                im2.save(self.fileOutPath)
                return (self.fileOutPath,os.path.getsize(self.fileOutPath))
            else:
                im2.save(self.fileInputPath)
                return (self.fileInputPath,os.path.getsize(self.fileInputPath))
        else:
            return True

    def Compress_Picture(self):
        thr = threading.Thread(target=self.SavePic)
        thr.start()

if __name__ == "__main__":
    tag = sys.argv[1:]
    savepic = Compress_Pic_or_Video(tag[0],tag[1],tag[2])
    print(savepic.Compress_Picture())

相关链接

如果出现了任何问题,请将问题出现的情景发送到邮箱 moriarty0305@icloud.com

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章