fix(pil): 修复 PIL Image 资源泄漏

Image.open() 后未 close() 导致文件句柄泄漏,用 _raw + try/finally 模式修复。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Sonnet 4.5 committed 2026-05-23 22:42:22 +08:00
1 parent b1fa6af9ce
commit c3746b0207
2 files changed
+34 -16

No files matched your search

@@ -72,11 +72,17 @@ def analyse_pic_word(
cache_key = None
# 加载图片
_pic_raw = None
img = None
try:
img = Image.open(pic_path)
img.load()
_pic_raw = Image.open(pic_path)
_pic_raw.load()
img = _pic_raw.convert("RGB")
_pic_raw.close()
_pic_raw = None
except (IOError, OSError, UnidentifiedImageError):
if _pic_raw is not None:
_pic_raw.close()
return ("", None) if return_confidence else ""
if img is None:
@@ -86,10 +92,11 @@ def analyse_pic_word(
# 外层"放大+锐化+对比度增强"反而会引入伪影,让识别变差。
# 因此默认走原图。仅在 change_color=1/2 业务显式要求二值化时才做。
if change_color in (1, 2):
old = img
img = img.convert("L")
old.close()
thresh = 128 if change_color == 1 else 180
img = img.point(lambda x, t=thresh: 0 if int(x) < t else 255)
img = img.convert("RGB")
else:
img = img.convert("RGB")
@@ -211,9 +218,12 @@ def _save_debug_preprocessed(
try:
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
full_screenshot = Image.open(screenshot_path)
full_screenshot.load()
full_screenshot = full_screenshot.convert("RGB")
_raw = Image.open(screenshot_path)
try:
_raw.load()
full_screenshot = _raw.convert("RGB")
finally:
_raw.close()
except Exception:
pass
@@ -284,9 +294,12 @@ def _save_debug_after_ocr(
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
full_screenshot = Image.open(screenshot_path)
full_screenshot.load()
full_screenshot = full_screenshot.convert("RGB")
_raw = Image.open(screenshot_path)
try:
_raw.load()
full_screenshot = _raw.convert("RGB")
finally:
_raw.close()
except Exception:
pass
@@ -46,15 +46,17 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
path = path_config.get_screenshot_path()
try:
pic = Image.open(path)
pic.load() # Force load to catch truncated files early
_raw = Image.open(path)
try:
_raw.load() # Force load to catch truncated files early
pic = _raw.convert("RGBA")
finally:
_raw.close()
except (OSError, IOError, SyntaxError):
# Handle truncated image files
return False
except Exception:
return False
pic = pic.convert("RGBA")
pix = pic.load()
w, h = pic.size
@@ -237,9 +239,12 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
pic_check = Image.open(pic_path)
pic_check.load()
pic_rgb_check = pic_check.convert("RGB")
_raw = Image.open(pic_path)
try:
_raw.load()
pic_rgb_check = _raw.convert("RGB")
finally:
_raw.close()
width, height = pic_rgb_check.size
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)