Skip to content

Commit f98fde7

Browse files
authored
Merge pull request #6522 from bibinhashley/ImageOps.contain-function-issue-in-finding-new-size
2 parents 920bcec + cf4017b commit f98fde7

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

Tests/test_imageops.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,16 @@ def test_contain(new_size):
110110
assert new_im.size == (256, 256)
111111

112112

113+
def test_contain_round():
114+
im = Image.new("1", (43, 63), 1)
115+
new_im = ImageOps.contain(im, (5, 7))
116+
assert new_im.width == 5
117+
118+
im = Image.new("1", (63, 43), 1)
119+
new_im = ImageOps.contain(im, (7, 5))
120+
assert new_im.height == 5
121+
122+
113123
def test_pad():
114124
# Same ratio
115125
im = hopper()
@@ -130,6 +140,15 @@ def test_pad():
130140
)
131141

132142

143+
def test_pad_round():
144+
im = Image.new("1", (1, 1), 1)
145+
new_im = ImageOps.pad(im, (4, 1))
146+
assert new_im.load()[2, 0] == 1
147+
148+
new_im = ImageOps.pad(im, (1, 4))
149+
assert new_im.load()[0, 2] == 1
150+
151+
133152
def test_pil163():
134153
# Division by zero in equalize if < 255 pixels in image (@PIL163)
135154

src/PIL/ImageOps.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -255,11 +255,11 @@ def contain(image, size, method=Image.Resampling.BICUBIC):
255255

256256
if im_ratio != dest_ratio:
257257
if im_ratio > dest_ratio:
258-
new_height = int(image.height / image.width * size[0])
258+
new_height = round(image.height / image.width * size[0])
259259
if new_height != size[1]:
260260
size = (size[0], new_height)
261261
else:
262-
new_width = int(image.width / image.height * size[1])
262+
new_width = round(image.width / image.height * size[1])
263263
if new_width != size[0]:
264264
size = (new_width, size[1])
265265
return image.resize(size, resample=method)
@@ -292,10 +292,10 @@ def pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5
292292
else:
293293
out = Image.new(image.mode, size, color)
294294
if resized.width != size[0]:
295-
x = int((size[0] - resized.width) * max(0, min(centering[0], 1)))
295+
x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))
296296
out.paste(resized, (x, 0))
297297
else:
298-
y = int((size[1] - resized.height) * max(0, min(centering[1], 1)))
298+
y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))
299299
out.paste(resized, (0, y))
300300
return out
301301

0 commit comments

Comments
 (0)