fix: mitigating WARNING router.py:1421:9 [cfg-resource-leak] — Image.open acquires file handle but not all exit paths release it
Some checks failed
NYX Security Scan / nyx-scan (pull_request) Failing after 6m57s
Some checks failed
NYX Security Scan / nyx-scan (pull_request) Failing after 6m57s
This commit is contained in:
parent
84e3b30f2f
commit
6c869aa305
1 changed files with 20 additions and 20 deletions
40
router.py
40
router.py
|
|
@ -1418,30 +1418,30 @@ def resize_image_if_needed(image_data):
|
||||||
pass
|
pass
|
||||||
# Decode the base64 image data
|
# Decode the base64 image data
|
||||||
image_bytes = base64.b64decode(image_data)
|
image_bytes = base64.b64decode(image_data)
|
||||||
image = Image.open(io.BytesIO(image_bytes))
|
with Image.open(io.BytesIO(image_bytes)) as image:
|
||||||
if image.mode not in ("RGB", "L"):
|
if image.mode not in ("RGB", "L"):
|
||||||
image = image.convert("RGB")
|
image = image.convert("RGB")
|
||||||
|
|
||||||
# Get current size
|
# Get current size
|
||||||
width, height = image.size
|
width, height = image.size
|
||||||
|
|
||||||
# Calculate the new dimensions while maintaining aspect ratio
|
# Calculate the new dimensions while maintaining aspect ratio
|
||||||
if width > 512 or height > 512:
|
if width > 512 or height > 512:
|
||||||
aspect_ratio = width / height
|
aspect_ratio = width / height
|
||||||
if aspect_ratio > 1: # Width is larger
|
if aspect_ratio > 1: # Width is larger
|
||||||
new_width = 512
|
new_width = 512
|
||||||
new_height = int(512 / aspect_ratio)
|
new_height = int(512 / aspect_ratio)
|
||||||
else: # Height is larger
|
else: # Height is larger
|
||||||
new_height = 512
|
new_height = 512
|
||||||
new_width = int(512 * aspect_ratio)
|
new_width = int(512 * aspect_ratio)
|
||||||
|
|
||||||
image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
||||||
|
|
||||||
# Encode the resized image back to base64
|
# Encode the resized image back to base64
|
||||||
buffered = io.BytesIO()
|
buffered = io.BytesIO()
|
||||||
image.save(buffered, format="PNG")
|
image.save(buffered, format="PNG")
|
||||||
resized_image_data = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
resized_image_data = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
||||||
return resized_image_data
|
return resized_image_data
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error processing image: {e}")
|
print(f"Error processing image: {e}")
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue