From 7e1b52fb578144dea3093d5f81e1aa36c8dcc56d Mon Sep 17 00:00:00 2001 From: Nemo2011 Date: Mon, 3 Feb 2025 11:33:00 +0800 Subject: [PATCH] fix: audio_uploader.upload_cover feat: Picture.resize --- bilibili_api/audio_uploader.py | 6 +++--- bilibili_api/utils/picture.py | 25 ++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/bilibili_api/audio_uploader.py b/bilibili_api/audio_uploader.py index cd869901..7f577b35 100644 --- a/bilibili_api/audio_uploader.py +++ b/bilibili_api/audio_uploader.py @@ -825,10 +825,10 @@ async def upload_cover(cover: Picture, credential: Credential) -> str: """ api = _API["image"] # 小于 3MB - raise_for_statement(os.path.getsize(cover) < 1024 * 1024 * 3, "3MB size limit") + raise_for_statement(len(cover.content) < 1024 * 1024 * 3, "3MB size limit") # 宽高比 1:1 raise_for_statement( - cover.width == cover.height, "width == height, 600 * 600 recommanded" + cover.width == cover.height, "width == height, 600 * 600 recommended" ) - files = {"file": cover.content} + files = {"file": cover._to_biliapifile()} return await Api(**api, credential=credential).update_files(**files).result diff --git a/bilibili_api/utils/picture.py b/bilibili_api/utils/picture.py index f409cf8f..0b90fe02 100644 --- a/bilibili_api/utils/picture.py +++ b/bilibili_api/utils/picture.py @@ -20,7 +20,7 @@ class Picture: imageType (str) : 格式,例如: png - size (Any) : 尺寸 + size (Any) : 大小。单位 KB url (str) : 图片链接 @@ -188,6 +188,29 @@ def convert_format(self, new_format: str) -> "Picture": self.__set_picture_meta_from_bytes(new_format) return self + def resize(self, width: int, height: int) -> "Picture": + """ + 调整大小 + + Args: + width (int): 宽度 + height (int): 高度 + + Returns: + Picture: `self` + """ + tmp_dir = tempfile.gettempdir() + img_path = os.path.join(tmp_dir, "test." + self.imageType) + open(img_path, "wb").write(self.content) + img = Image.open(img_path) + img = img.resize((width, height)) + new_img_path = os.path.join(tmp_dir, "test." + self.imageType) + img.save(new_img_path) + with open(new_img_path, "rb") as file: + self.content = file.read() + self.__set_picture_meta_from_bytes(self.imageType) + return self + def to_file(self, path: str) -> "Picture": """ 下载图片至本地。