Update app.py
Browse files
app.py
CHANGED
|
@@ -122,25 +122,36 @@ def create_base64_markdown_image(image_url, max_width=None, max_height=None):
|
|
| 122 |
|
| 123 |
image_data = response.content
|
| 124 |
image = Image.open(BytesIO(image_data))
|
|
|
|
| 125 |
|
| 126 |
if max_width or max_height:
|
|
|
|
| 127 |
if max_width and max_height:
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
elif max_width:
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
| 133 |
elif max_height:
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
| 137 |
|
| 138 |
buffered = BytesIO()
|
| 139 |
image.save(buffered, format="PNG")
|
| 140 |
compressed_image_data = buffered.getvalue()
|
| 141 |
|
| 142 |
base64_encoded = base64.b64encode(compressed_image_data).decode('utf-8')
|
| 143 |
-
mime_type = "image/png"
|
| 144 |
markdown_image_link = f""
|
| 145 |
logging.info(f"Created base64 markdown image link.")
|
| 146 |
return markdown_image_link
|
|
|
|
| 122 |
|
| 123 |
image_data = response.content
|
| 124 |
image = Image.open(BytesIO(image_data))
|
| 125 |
+
original_width, original_height = image.size
|
| 126 |
|
| 127 |
if max_width or max_height:
|
| 128 |
+
# Calculate the new dimensions while maintaining aspect ratio
|
| 129 |
if max_width and max_height:
|
| 130 |
+
# If both max_width and max_height are provided, scale to fit within the box
|
| 131 |
+
ratio = min(max_width / original_width, max_height / original_height)
|
| 132 |
+
new_width = int(original_width * ratio)
|
| 133 |
+
new_height = int(original_height * ratio)
|
| 134 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
| 135 |
+
|
| 136 |
elif max_width:
|
| 137 |
+
# Scale based on max_width
|
| 138 |
+
ratio = max_width / original_width
|
| 139 |
+
new_width = max_width
|
| 140 |
+
new_height = int(original_height * ratio)
|
| 141 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
| 142 |
elif max_height:
|
| 143 |
+
# Scale based on max_height
|
| 144 |
+
ratio = max_height / original_height
|
| 145 |
+
new_height = max_height
|
| 146 |
+
new_width = int(original_width * ratio)
|
| 147 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
| 148 |
|
| 149 |
buffered = BytesIO()
|
| 150 |
image.save(buffered, format="PNG")
|
| 151 |
compressed_image_data = buffered.getvalue()
|
| 152 |
|
| 153 |
base64_encoded = base64.b64encode(compressed_image_data).decode('utf-8')
|
| 154 |
+
mime_type = "image/png" # Always use image/png since we are saving as png
|
| 155 |
markdown_image_link = f""
|
| 156 |
logging.info(f"Created base64 markdown image link.")
|
| 157 |
return markdown_image_link
|