How can a preview fit a box without padding or cropping?

contain preserves aspect ratio and returns only the scaled picture inside the requested bounds.

Pixel experiment and interpretation

An 8-by-4 cover inside a 4-by-4 slot needs only a 4-by-2 file. A batch requiring equal tensor shapes still needs padding.

from PIL import Image, ImageOps

ImageOps.contain(Image.new('RGB',(8,4)),(4,4)).size

Result (4, 2)

中文

如何得到完整可见且不带填充的商品预览?

contain 等比例缩放到上限内,输出尺寸跟随图片比例。

像素实验与适用边界

把 8×4 的封面放进 4×4 的槽位,文件只需保存 4×2 的内容。批处理若要求同尺寸张量,还要另行补边。

from PIL import Image, ImageOps

ImageOps.contain(Image.new('RGB',(8,4)),(4,4)).size

结果 (4, 2)

References / 参考来源

Keep reading / 继续阅读