Commit 52de939

benny-dou <60535774+benny-dou@users.noreply.github.com>
2025-02-25 15:18:37
fix(image): close image after processing
1 parent a30755f
Changed files (1)
src/multimedia.py
@@ -92,6 +92,7 @@ def split_long_img(path: str | Path | None, max_height: float = 2500, max_ratio:
                 logger.debug(f"split {idx} saved to {save_path}")
             if delete:
                 path.unlink(missing_ok=True)
+        img.close()
     except Exception as e:
         logger.error(f"Failed to split long image: {e}")
         return [path]
@@ -308,6 +309,7 @@ def convert_jpg_via_pillow(path: str | Path | None, *, delete: bool = True) -> t
     try:
         img = Image.open(path)
         img.convert("RGB").save(save_path)
+        img.close()
     except Exception as e:
         logger.error(f"Failed convert {path.name} -> {save_path.name}: {e}")
         return False, path
@@ -371,7 +373,7 @@ def convert_img_match_telegram_rules(path: str | Path, num_bytes: int = 10485760
         return Path("")
     min_ratio = 1 / max_ratio
     filesize = path.stat().st_size
-    save_path = path.with_stem(f"{path.stem}_reduced")
+    save_path = path.with_stem(f"{path.stem}X")
     try:
         img = Image.open(path)
         width, height = img.size
@@ -379,8 +381,9 @@ def convert_img_match_telegram_rules(path: str | Path, num_bytes: int = 10485760
         logger.trace(f"{path.name}: {width}x{height} (r={ratio:.2f}), {filesize} bytes ({readable_size(path=path)})")
         if filesize < num_bytes and width + height < wh_total and min_ratio < ratio < max_ratio:
             logger.debug(f"Image is already under limit: {path.name}")
+            img.close()
             return path
-        new_width = round(0.9 * width)
+        new_width = round(0.85 * width)
         if ratio > max_ratio:
             new_height = round(new_width / max_ratio)
         elif ratio < min_ratio:
@@ -390,6 +393,7 @@ def convert_img_match_telegram_rules(path: str | Path, num_bytes: int = 10485760
 
         img = img.resize((new_width, new_height))
         img.save(save_path)
+        img.close()
     except Exception as e:
         logger.error(f"Failed to reduce image size: {path}, {e}")
         return path