-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_resize_image.py
80 lines (71 loc) · 2.49 KB
/
test_resize_image.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Resize an image."""
from argparse import ArgumentParser
from PIL import Image
class TestResizeImage: # pylint: disable=too-few-public-methods
"""Resize images."""
def __init__(self):
"""Resize images."""
parser = ArgumentParser()
parser.add_argument(
"-i",
"--input_filename",
dest="input_filename",
help="Input filename. Default to empty.",
default="",
)
parser.add_argument(
"-o",
"--output_filename",
dest="output_filename",
help="Output filename. Default to movie.",
default="movie",
)
options = parser.parse_args()
image_max_width = 1920
image_max_height = 1280
self.resize_image(
options.input_filename,
options.output_filename,
image_max_width,
image_max_height,
)
@classmethod
def resize_image(cls, input_filename, output_filename, max_width, max_height):
"""Resize an image."""
print(f"Resizing {input_filename}")
orig_image = Image.open(input_filename)
orig_size = orig_image.size
new_size = (max_width, max_height)
new_image = Image.new("RGB", new_size)
if orig_size[0] > max_width or orig_size[1] > max_height:
print(
f"Original size is ({orig_size[0]}, {orig_size[1]}) and "
f"max size is ({max_width}, {max_height})"
)
w_ratio = max_width / orig_size[0]
h_ratio = max_height / orig_size[1]
scale_ratio = min(w_ratio, h_ratio)
print(
f"Resized {input_filename} using ratio of {scale_ratio} "
f"since w_ratio = {w_ratio} and h_ratio = {h_ratio}"
)
orig_image = orig_image.resize(
((int(orig_size[0] * scale_ratio)), int(orig_size[1] * scale_ratio)),
Image.ANTIALIAS,
)
print(
f"orig_image is now ({int(orig_size[0] * scale_ratio)}, "
f"{int(orig_size[1] * scale_ratio)})"
)
new_image.paste(
orig_image,
(
int((new_size[0] - orig_size[0] * scale_ratio) / 2),
int((new_size[1] - orig_size[1] * scale_ratio) / 2),
),
)
new_image.save(output_filename)
if __name__ == "__main__":
TestResizeImage()