diff options
author | Kyomotoi <[email protected]> | 2021-01-26 18:43:13 +0800 |
---|---|---|
committer | Kyomotoi <[email protected]> | 2021-01-26 18:43:13 +0800 |
commit | 7640568a42493bc5a5e44bc82b1ecfa87e51c5f1 (patch) | |
tree | 60f29b756d58b085c95573515d3e4bd6f41426a8 /ATRI/utils.py | |
parent | d0d31b2630697c97e848f00142f06b81f63b255a (diff) | |
download | ATRI-7640568a42493bc5a5e44bc82b1ecfa87e51c5f1.tar.gz ATRI-7640568a42493bc5a5e44bc82b1ecfa87e51c5f1.tar.bz2 ATRI-7640568a42493bc5a5e44bc82b1ecfa87e51c5f1.zip |
[Update]
Diffstat (limited to 'ATRI/utils.py')
-rw-r--r-- | ATRI/utils.py | 37 |
1 files changed, 32 insertions, 5 deletions
diff --git a/ATRI/utils.py b/ATRI/utils.py index b0f1b12..7ded644 100644 --- a/ATRI/utils.py +++ b/ATRI/utils.py @@ -1,9 +1,14 @@ +import os import yaml from datetime import datetime from pathlib import Path +from PIL import ImageFile +import PIL.Image as Image +from .exceptions import InvalidWriteText -def loadYaml(file: Path) -> dict: + +def load_yaml(file: Path) -> dict: ''' 读取yaml文件 :return: dict @@ -13,7 +18,7 @@ def loadYaml(file: Path) -> dict: return data -def countList(lst: list, aim) -> int: +def count_list(lst: list, aim) -> int: ''' 检查某列表中目标出现的次数 :return: int @@ -25,7 +30,7 @@ def countList(lst: list, aim) -> int: return count -def delListAim(lst: list, aim) -> list: +def del_list_aim(lst: list, aim) -> list: ''' 删除某列表中所有目标元素 :return: list @@ -35,7 +40,7 @@ def delListAim(lst: list, aim) -> list: return lst -def nowTime() -> float: +def now_time() -> float: ''' 获取当前时间(小时) :return: float @@ -44,4 +49,26 @@ def nowTime() -> float: hour = now_.hour minute = now_.minute now = hour + minute / 60 - return now
\ No newline at end of file + return now + +def compress_image(out_file: str, kb=500, quality=85, k=0.9) -> str: + ''' + 压缩图片 + :return: img file + ''' + o_size = os.path.getsize(out_file) // 1024 + if o_size <= kb: + return out_file + + ImageFile.LOAD_TRUNCATED_IMAGES = True # type: ignore + while o_size > kb: + img = Image.open(out_file) + x, y = img.size + out = img.resize((int(x * k), int(y * k)), Image.ANTIALIAS) + try: + out.save(out_file, quality=quality) + except InvalidWriteText: + raise InvalidWriteText('Writing file failed!') + break + o_size = os.path.getsize(out_file) // 1024 + return out_file |