Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, filling empty with data from image. Args: image: The image to resize. width: The width to resize the image to.
(
self,
image: PIL.Image.Image,
width: int,
height: int,
)
| 259 | return x1, y1, x2, y2 |
| 260 | |
| 261 | def _resize_and_fill( |
| 262 | self, |
| 263 | image: PIL.Image.Image, |
| 264 | width: int, |
| 265 | height: int, |
| 266 | ) -> PIL.Image.Image: |
| 267 | """ |
| 268 | Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, filling empty with data from image. |
| 269 | |
| 270 | Args: |
| 271 | image: The image to resize. |
| 272 | width: The width to resize the image to. |
| 273 | height: The height to resize the image to. |
| 274 | """ |
| 275 | |
| 276 | ratio = width / height |
| 277 | src_ratio = image.width / image.height |
| 278 | |
| 279 | src_w = width if ratio < src_ratio else image.width * height // image.height |
| 280 | src_h = height if ratio >= src_ratio else image.height * width // image.width |
| 281 | |
| 282 | resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"]) |
| 283 | res = Image.new("RGB", (width, height)) |
| 284 | res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2)) |
| 285 | |
| 286 | if ratio < src_ratio: |
| 287 | fill_height = height // 2 - src_h // 2 |
| 288 | if fill_height > 0: |
| 289 | res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0)) |
| 290 | res.paste( |
| 291 | resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)), |
| 292 | box=(0, fill_height + src_h), |
| 293 | ) |
| 294 | elif ratio > src_ratio: |
| 295 | fill_width = width // 2 - src_w // 2 |
| 296 | if fill_width > 0: |
| 297 | res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0)) |
| 298 | res.paste( |
| 299 | resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)), |
| 300 | box=(fill_width + src_w, 0), |
| 301 | ) |
| 302 | |
| 303 | return res |
| 304 | |
| 305 | def _resize_and_crop( |
| 306 | self, |