How do you add asymmetric margins to an image?

expand accepts left, top, right and bottom border widths and grows the canvas without rescaling the source.

Pixel experiment and interpretation

Reserve two cells on the left and one on top. The original corner moves to (2,1), so its annotation needs the same translation.

from PIL import Image, ImageOps

def row(values):
    return Image.frombytes('L', (len(values), 1), bytes(values))

im=ImageOps.expand(row([99]),border=(2,1,0,0),fill=0)
(im.size,im.getpixel((2,1)))

Result ((3, 2), 99)

中文

如何在四侧添加不同宽度的图像边框?

expand 接受左、上、右、下四个边宽并扩张画布,原内容不缩放。

像素实验与适用边界

给标签图左侧留两格、上侧留一格,原先的左上角移动到 (2,1)。外接框的坐标也需要平移。

from PIL import Image, ImageOps

def row(values):
    return Image.frombytes('L', (len(values), 1), bytes(values))

im=ImageOps.expand(row([99]),border=(2,1,0,0),fill=0)
(im.size,im.getpixel((2,1)))

结果 ((3, 2), 99)

References / 参考来源

Keep reading / 继续阅读