mirror of
https://github.com/AstrBotDevs/AstrBot
synced 2026-07-15 17:30:13 +08:00
fix(core): downscale oversized images (#7807)
* fix(core): downscale oversized images * refactor: share image max-size check helper * Delete tests/unit/test_media_utils_compress_image.py --------- Co-authored-by: Weilong Liao <37870767+Soulter@users.noreply.github.com>
This commit is contained in:
@@ -436,19 +436,30 @@ async def compress_image(
|
||||
optimize = IMAGE_COMPRESS_DEFAULT_OPTIMIZE
|
||||
min_file_size_bytes = int(IMAGE_COMPRESS_DEFAULT_MIN_FILE_SIZE_MB * 1024 * 1024)
|
||||
data = None
|
||||
|
||||
def _exceeds_max_size(source: bytes | Path) -> bool:
|
||||
try:
|
||||
fp = io.BytesIO(source) if isinstance(source, bytes) else source
|
||||
with PILImage.open(fp) as opened_img:
|
||||
return max(opened_img.size) > max_size
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
# Skip compression for remote images and return the original value.
|
||||
if url_or_path.startswith("http"):
|
||||
return url_or_path
|
||||
elif url_or_path.startswith("data:image"):
|
||||
_header, encoded = url_or_path.split(",", 1)
|
||||
data = base64.b64decode(encoded)
|
||||
if len(data) < min_file_size_bytes:
|
||||
if len(data) < min_file_size_bytes and not _exceeds_max_size(data):
|
||||
return url_or_path
|
||||
else:
|
||||
local_path = Path(url_or_path)
|
||||
if not local_path.exists():
|
||||
return url_or_path
|
||||
if local_path.stat().st_size < min_file_size_bytes:
|
||||
if local_path.stat().st_size < min_file_size_bytes and not _exceeds_max_size(
|
||||
local_path
|
||||
):
|
||||
return url_or_path
|
||||
with local_path.open("rb") as f:
|
||||
data = f.read()
|
||||
|
||||
Reference in New Issue
Block a user