import pathlib
from datetime import datetime
from PIL import Image
import os
import pillow_heif
def get_time():
"""
获取系统时间
:return:
"""
date_time = datetime.today()
ymd = date_time.strftime('%Y-%m-%d')
hh = date_time.strftime('%H')
mm = date_time.strftime('%M')
ss = date_time.strftime('%S')
time_str = '{} {}_{}_{}'.format(ymd, hh, mm, ss)
return time_str
def get_all_heic_imgs(source_path):
"""
遍历源文件夹及子文件夹,获取所有HEIC格式(不区分大小写)的图片
:return:
"""
file_list = []
if os.path.isdir(source_path):
for root, dir_names, file_names in os.walk(source_path):
for file_name in file_names:
# 文件后缀名
filetype = pathlib.Path(file_name).suffix
# 文件名(不带后缀)
filename = pathlib.Path(file_name).name.split(".")[-2]
if filetype in ['.heic', '.HEIC']:
# 文件的完整目录
filepath = os.path.join(root, file_name)
file_list.append({"filepath": filepath, "root": root, "filename": filename})
else:
print('输入文件路径错误! [' + source_path + ']')
return file_list
pass
def convert_heic_to_jpg(file_list):
if file_list.__len__() != 0:
for file in file_list:
# 使用pillow_heif读取HEIC文件
heif_file = pillow_heif.read_heif(file.get('filepath'))
# 将HEIC图像转换为PIL图像
image = Image.frombytes(mode=heif_file.mode, size=heif_file.size, data=heif_file.data)
if image.mode == 'RGBA':
# 文件保存完整目录
output_file = '{}\\{}_{}.PNG'.format(file.get('root'), file.get('filename'), get_time())
# print(output_file)
# 保存为JPEG文件
image.save(output_file, format='PNG')
elif image.mode == 'RGB':
# 文件保存完整目录
output_file = '{}\\{}_{}.JPG'.format(file.get('root'), file.get('filename'), get_time())
# print(output_file)
# 保存为JPEG文件
image.save(output_file, format='JPEG')
# 示例:读取HEIC文件并转换为JPEG
convert_heic_to_jpg(get_all_heic_imgs('F:\HEIC'))
使用pillow_heif 库将苹果手机HEIC格式照片转换为JPG格式
最新推荐文章于 2024-12-29 10:42:28 发布