工作中需要把一些bmp圖轉換為jpg,部分資料是使用opencv,但安裝起來不方便,估使用其他方式。
import os.path
from PIL import Image
from io import BytesIO
def scanDir(dirPath: str)->list:
"""掃描目錄"""
fileList = []
for top, dirs, nondirs in os.walk(dirPath):
for item in nondirs:
if item.split('.)[-1] == 'bmp':
fileList.append(os.path.join(top, item))
return fileList
def bmp2jpg(filePath):
fileLst = scanDir(filePath)
for oneFile in fileLst:
bmp = Image.open(oneFile)
output_buffer = BytesIO()
bmp.save(output_buffer,format ='JPEG')
byte_data = output_buffer.getvalue()
a = os.path.splitext(oneFile)[0]
tmpUrl = f'{a}.jpg'
try:
with open(tmpUrl, 'wb') as f:
f.write(byte_data)
except Exception as e:
pass