使用Python批量转换图片格式
生活随笔
收集整理的這篇文章主要介紹了
使用Python批量转换图片格式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
PNG 創(chuàng)建于 1995 年,是用于在網(wǎng)絡(luò)上傳輸圖像的 GIF 格式的免費(fèi)替代品。因?yàn)镻NG沒專利,所以編輯和查看PNG也不需要許可。PNG圖像在壓縮時(shí)不會丟失任何數(shù)據(jù),編碼、解碼方式一樣。與JPEG 文件等有損選項(xiàng)相比,這是一個(gè)很大的優(yōu)勢。
所以,要想把其它格式的圖片轉(zhuǎn)換為PNG格式是很方便的。除了一種情況,那就是圖片比較多的時(shí)候。這時(shí)需要一些工具來幫助我們批量轉(zhuǎn)換。很多解決方案都需要安裝什么軟件,下面這種,額……也需要安裝腳本解釋器,除此之外還得安裝一個(gè)包:
pip install pillow然后編寫和執(zhí)行腳本:
from multiprocessing import Pool import os import re from PIL import Imagedef save_single(root: str, source_filename: str, suffix: str, target_path: str, target_suffix: str='png' ):try:img = Image.open(os.path.join(root, source_filename+suffix))img = img.convert('RGB')img.save(os.path.join(target_path, f'{source_filename}.{target_suffix}'), target_suffix)except Exception as e:print(e)return ereturn Falsedef copy_single(root: str, source_filename: str, target_path: str ):try:with open(os.path.join(root, source_filename), 'rb') as file:read = file.read()with open(os.path.join(target_path, source_filename), 'wb') as file:file.write(read)except Exception as e:print(e)return ereturn Falsedef run(source_path: str, target_path: str, pool):file_paths = []source_path_len = len(source_path)if not(source_path.endswith('/') or source_path.endswith('\\')):source_path_len += 1if not os.path.exists(target_path):os.makedirs(target_path)for root, directories, files in os.walk(source_path):for file in files:path = root[source_path_len:] # 去掉要被替換掉的目錄前綴target_directory = os.path.join(target_path, path) # 這是新目錄,要保存的位置file_paths.append((root, file, target_directory))for directory in directories: # 創(chuàng)建目錄,要是把所有文件保存在同目錄下,同名文件會沖突source_path = os.path.join(root, directory)path = source_path[source_path_len:]target_directory = os.path.join(target_path, path)if not os.path.exists(target_directory):os.makedirs(target_directory)for root, file, target in file_paths:fname, suffix = os.path.splitext(file)lower_suffix = suffix.lower()if lower_suffix in ('.jpg', '.jpeg', '.bmp'):pool.apply_async(save_single, (root, fname, suffix, target))else:pool.apply_async(copy_single, (root, file, target))SOURCE_PATH = '/home/ubuntu/example/Download' # 一個(gè)目錄,腳本會遞歸地訪問這文件夾里的圖片 TARGET_PATH = '/home/ubuntu/example/project/assets' # 腳本會在轉(zhuǎn)換的時(shí)候把原來目錄的結(jié)構(gòu)都復(fù)刻進(jìn)來,也就是說轉(zhuǎn)換前后各個(gè)圖片的相對位置沒變if __name__ == "__main__":pool = Pool(8) # 這個(gè)8是進(jìn)程池的大小,根據(jù)電腦核數(shù)和內(nèi)存以及磁盤轉(zhuǎn)速來選run(SOURCE_PATH, TARGET_PATH, pool)pool.close()pool.join()總結(jié)
以上是生活随笔為你收集整理的使用Python批量转换图片格式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NV12转化为BMP函数
- 下一篇: GB35114---基于openssl加