Skip to content

Commit

Permalink
修复处理非英文字符文件闪退的问题 (#28)
Browse files Browse the repository at this point in the history
* 修复处理非英文字符文件闪退的问题
  • Loading branch information
leslievan authored Apr 17, 2023
1 parent 6b63ac1 commit 808d44a
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 38 deletions.
3 changes: 2 additions & 1 deletion image_container.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime
from pathlib import Path

from PIL import Image
from PIL.Image import Transpose
Expand All @@ -7,7 +8,7 @@


class ImageContainer(object):
def __init__(self, path):
def __init__(self, path: Path):
self.img = Image.open(path)
self.exif = get_exif(path)

Expand Down
6 changes: 3 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
from pathlib import Path

from tqdm import tqdm

Expand Down Expand Up @@ -147,8 +148,7 @@ def processing():
layout = Layout(config['layout'])
print('当前共有 {} 张图片待处理'.format(len(file_list)))
processor = ImageProcessor(font, bold_font)
for file in tqdm(file_list):
source_path = os.path.join(input_dir, file)
for source_path in tqdm(file_list):
# 打开图片
container = ImageContainer(source_path)

Expand All @@ -175,7 +175,7 @@ def processing():
'tlr')

# 保存图片
target_path = os.path.join(output_dir, file)
target_path = Path(output_dir).joinpath(source_path.name)
watermark.save(target_path, quality=quality)
container.close()
watermark.close()
Expand Down
2 changes: 1 addition & 1 deletion main.spec
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,5 @@ coll = COLLECT(
strip=False,
upx=True,
upx_exclude=[],
name='semi-utils-1_4_14',
name='semi-utils-1_4_15',
)
81 changes: 48 additions & 33 deletions utils.py
Original file line number Diff line number Diff line change
@@ -1,49 +1,37 @@
import os
import platform
import re
import subprocess
from pathlib import Path

import piexif
from PIL import Image
from PIL.ExifTags import TAGS
import re
import subprocess
import platform

if platform.system() == 'Windows':
exiftool_path = './exiftool/exiftool.exe'
encoding = 'gbk'
else:
exiftool_path = './exiftool/exiftool'
encoding = 'utf-8'


def get_file_list(path):
"""
获取文件列表
:param path: 路径
:return: 文件名
"""
file_list = [file for file in os.listdir(path) if
'jpg' in file or 'jpeg' in file or 'JPG' in file or 'JPEG' in file]
return file_list
path = Path(path)
return [file_path for file_path in path.iterdir()
if file_path.is_file() and file_path.suffix in ['.jpg', '.jpeg', '.JPG', '.JPEG']]


def get_exif(path):
"""
获取exif信息
:param image:
:param path:
:return:
"""
output = subprocess.check_output([exiftool_path, path])
exif_dict = {}
for line in output.splitlines():
# 将每一行按冒号分隔成键值对
line = line.decode('utf-8') # 将 bytes 转换为 str
kv_pair = line.split(':')
if len(kv_pair) < 2:
continue
key = kv_pair[0].strip()
value = ':'.join(kv_pair[1:]).strip()
# 将键中的空格移除
key = re.sub(r'\s+', '', key)
key = re.sub(r'/', '', key)
# 将键值对添加到字典中
exif_dict[key] = value

_exif = {}
with Image.open(path) as image:
Expand All @@ -52,26 +40,53 @@ def get_exif(path):
for attr, value in info.items():
decoded_attr = TAGS.get(attr, attr)
_exif[decoded_attr] = value
try:
# 如果 exif 中不存在镜头信息,用 exiftool 读取
if 'LensModel' not in _exif:
output = subprocess.check_output([exiftool_path, '-charset', 'UTF8', path])

output = output.decode(encoding)
lines = output.splitlines()
utf8_lines = [line for line in lines]

exif_dict = {}
for line in utf8_lines:
# 将每一行按冒号分隔成键值对
kv_pair = line.split(':')
if len(kv_pair) < 2:
continue
key = kv_pair[0].strip()
value = ':'.join(kv_pair[1:]).strip()
# 将键中的空格移除
key = re.sub(r'\s+', '', key)
key = re.sub(r'/', '', key)
# 将键值对添加到字典中
exif_dict[key] = value
if 'LensModel' in exif_dict:
_exif['LensModel'] = exif_dict['LensModel']
elif 'Lens' in exif_dict:
_exif['LensModel'] = exif_dict['Lens']
elif 'LensID' in exif_dict:
_exif['LensModel'] = exif_dict['LensID']
except UnicodeDecodeError as e:
print('UnicodeDecodeError: {}'.format(path))
pass
finally:
pass

if 'LensModel' in exif_dict:
_exif['LensModel'] = exif_dict['LensModel']
elif 'Lens' in exif_dict:
_exif['LensModel'] = exif_dict['Lens']
elif 'LensID' in exif_dict:
_exif['LensModel'] = exif_dict['LensID']
return _exif


def copy_exif_data(source_path, target_path):
try:
# 读取源照片的 exif 信息
src_exif = piexif.load(source_path)
src_exif = piexif.load(str(source_path))

# 将 exif 信息转换为字节串
src_exif_bytes = piexif.dump(src_exif)

# 将源照片的 exif 信息写入 target_path
piexif.insert(src_exif_bytes, target_path)
piexif.insert(src_exif_bytes, str(target_path))

except ValueError as e:
print("错误:{} exif 信息复制失败".format(source_path))
except ValueError:
pass

0 comments on commit 808d44a

Please sign in to comment.