Python如何將圖像音視頻等資源文件隱藏在代碼中(小技巧)
下午有同學(xué)Python學(xué)習(xí)群里說,使用pyinstaller打包源碼時(shí),因?yàn)榇a中使用了圖像、音頻、視頻等資源文件,無法將程序打包成單一的可執(zhí)行文件。有沒有方法將這些資源文件按保存在代碼中呢?我想了一下,應(yīng)該是可以的。于是乎,花了一個小時(shí),寫出了下面的代碼,算是拋磚引玉吧。
這段代碼可以將二進(jìn)制文件轉(zhuǎn)存為python腳本文件,供其他腳本引用。代碼最后附有使用的例子,演示用的圖片可以隨便照一張。除了轉(zhuǎn)存二進(jìn)制數(shù)據(jù),還提供了兩個方法:
- get_fp():返回二進(jìn)制的IO對象(類文件對象)
- save():保存為本地文件
# -*- coding: utf-8 -*- """以python模塊形式存儲、使用二進(jìn)制文件""" import os import base64 from io import BytesIO def bin2module(bin_file, py_file=None): """二進(jìn)制文件轉(zhuǎn)存為python模塊 bin_file - 二進(jìn)制文件名 py_file - 生成的模塊文件名,默認(rèn)使用二進(jìn)制文件名,僅更改后綴名 """ fpath, fname = os.path.split(bin_file) fn, ext = os.path.splitext(fname) if not py_file: py_file = os.path.join(fpath, '%s.py'%fn) with open(bin_file, 'rb') as fp: content = fp.read() content = base64.b64encode(content) content = content.decode('utf8') with open(py_file, 'w') as fp: fp.write('# -*- coding: utf-8 -*-\n\n') fp.write('import base64\n') fp.write('from io import BytesIO\n\n') fp.write('content = """%s"""\n\n'%content) fp.write('def get_fp():\n') fp.write(' return BytesIO(base64.b64decode(content.encode("utf8")))\n\n') fp.write('def save(file_name):\n') fp.write(' with open(file_name, "wb") as fp:\n') fp.write(' fp.write(base64.b64decode(content.encode("utf8")))\n') if __name__ == '__main__': """測試代碼""" # 將圖像文件轉(zhuǎn)存為img_demo.py bin2module('forever.png', 'demo.py') # 導(dǎo)入剛剛生成的demo模塊 import demo # 用pillow打開圖像,驗(yàn)證demo模塊的get_fp():返回二進(jìn)制的IO對象(類文件對象) from PIL import Image im = Image.open(demo.get_fp()) im.show() # 保存為本地文件,驗(yàn)證demo模塊的save():保存文件 demo.save('demo_save.png')
補(bǔ)充:下面看下Python實(shí)現(xiàn)將視頻按間隔截取為圖片(附代碼)
輸入:一段視頻。
輸出:取出的視頻幀。
準(zhǔn)備:新建一個文件夾,用來放置截出來視頻幀。
代碼實(shí)現(xiàn):
import cv2 import argparse import os def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Process pic') parser.add_argument('--input', help='video to process', dest='input', default=None, type=str) parser.add_argument('--output', help='pic to store', dest='output', default=None, type=str) #default為間隔多少幀截取一張圖片 parser.add_argument('--skip_frame', dest='skip_frame', help='skip number of video', default=100, type=int) #此處可更改提取幀的間隔 args = parser.parse_args(['--input','','--output','']) #此處添加路徑,input為輸入視頻的路徑 ,output為輸出存放圖片的路徑 return args def process_video(i_video, o_video, num): cap = cv2.VideoCapture(i_video) num_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT) expand_name = '.jpg' if not cap.isOpened(): print("Please check the path.") cnt = 0 count = 0 while 1: ret, frame = cap.read() cnt += 1 # how # many # frame # to # cut if cnt % num == 0: count += 1 cv2.imwrite(os.path.join(o_video, str(count) + expand_name), frame) if not ret: break if __name__ == '__main__': args = parse_args() if not os.path.exists(args.output): os.makedirs(args.output) print('Called with args:') print(args) process_video(args.input, args.output, args.skip_frame)
運(yùn)行起來非常容易,若是出錯請檢查 路徑書寫 是否正確。如下是一種絕對路徑的寫法舉例,前方加 r。
args = parser.parse_args(['--input', r'F:\data_video\IMG_4395.MOV', '--output', r'F:data_rgb_\video_to_frame'])
總結(jié)
以上所述是小編給大家介紹的Python如何將圖像音視頻等資源文件隱藏在代碼中(小技巧),希望對大家有所幫助!
相關(guān)文章
Python小游戲?qū)崿F(xiàn)實(shí)例之接蘋果
其實(shí)利用Python編寫的小游戲很簡單,下面這篇文章主要給大家介紹了關(guān)于Python小游戲?qū)崿F(xiàn)實(shí)例之接蘋果的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03Python如何使用WebSocket實(shí)現(xiàn)實(shí)時(shí)Web應(yīng)用
這篇文章主要介紹了Python使用WebSocket實(shí)現(xiàn)實(shí)時(shí)Web應(yīng)用,Django?Channels?提供了強(qiáng)大的功能,使得在?Django?中實(shí)現(xiàn)實(shí)時(shí)功能變得更加容易,你可以在此基礎(chǔ)上擴(kuò)展,添加更多功能和復(fù)雜的邏輯,需要的朋友可以參考下2024-08-08Python中print函數(shù)簡單使用總結(jié)
在本篇文章里小編給大家整理的是關(guān)于Python中怎么使用print函數(shù)的相關(guān)知識點(diǎn)內(nèi)容,需要的朋友們可以學(xué)習(xí)下。2019-08-08python數(shù)組復(fù)制拷貝的實(shí)現(xiàn)方法
這篇文章主要介紹了python數(shù)組復(fù)制拷貝的實(shí)現(xiàn)方法,實(shí)例分析了Python數(shù)組傳地址與傳值兩種復(fù)制拷貝的使用技巧,需要的朋友可以參考下2015-06-06使用Py2Exe for Python3創(chuàng)建自己的exe程序示例
今天小編就為大家分享一篇使用Py2Exe for Python3創(chuàng)建自己的exe程序示例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10Django數(shù)據(jù)映射(一對一,一對多,多對多)
本文主要介紹了Django數(shù)據(jù)映射(一對一,一對多,多對多),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08