使用Python批量转换图片格式
生活随笔
收集整理的這篇文章主要介紹了
使用Python批量转换图片格式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
PNG 創建于 1995 年,是用于在網絡上傳輸圖像的 GIF 格式的免費替代品。因為PNG沒專利,所以編輯和查看PNG也不需要許可。PNG圖像在壓縮時不會丟失任何數據,編碼、解碼方式一樣。與JPEG 文件等有損選項相比,這是一個很大的優勢。
所以,要想把其它格式的圖片轉換為PNG格式是很方便的。除了一種情況,那就是圖片比較多的時候。這時需要一些工具來幫助我們批量轉換。很多解決方案都需要安裝什么軟件,下面這種,額……也需要安裝腳本解釋器,除此之外還得安裝一個包:
pip install pillow然后編寫和執行腳本:
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: # 創建目錄,要是把所有文件保存在同目錄下,同名文件會沖突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' # 一個目錄,腳本會遞歸地訪問這文件夾里的圖片 TARGET_PATH = '/home/ubuntu/example/project/assets' # 腳本會在轉換的時候把原來目錄的結構都復刻進來,也就是說轉換前后各個圖片的相對位置沒變if __name__ == "__main__":pool = Pool(8) # 這個8是進程池的大小,根據電腦核數和內存以及磁盤轉速來選run(SOURCE_PATH, TARGET_PATH, pool)pool.close()pool.join()總結
以上是生活随笔為你收集整理的使用Python批量转换图片格式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NV12转化为BMP函数
- 下一篇: 2021-05-26python 批量更