如何计算偏移量以在网格中均匀显示图像?

How to calculate offsets to show images in a grid evenly?

我有一组图像(frame0.jpgframe15.jpg),我想在黄色背景的网格中显示:

from PIL import Image

# yellow background
img = Image.new("RGBA", (1920, 1080), (255, 216, 0, 255))
img_w, img_h = img.size
offset = 20

rows = 4
columns = 4

frame_w = img_w // rows - offset
frame_h = img_h // columns - offset
total_frames = rows * columns

x, y = 15, 15
for i in range(0, total_frames):
    frame_on_the_row = Image.open("frame" + str(i) + ".jpg", "r")
    img.paste(frame_on_the_row, (x, y))
    x += frame_w + 15  # its offset I choose empirically
    if x > img_w - frame_w:
        x = 15
        y += frame_h + 15

img.save("out.png")

输出示例:

如您所见,底部和右侧的黄色边框比其他黄色线条略宽。我怎样才能让它们都一样宽?

您用 20 计算了偏移量。我假设您通过减去 5 px 来确定 x, y = 15, 15,以将右侧和底部的线计算为 20 px。但是,您现在将其他设置为 15 px。

设置x, y = 16, 16将产生偶数行,全部为 16 像素宽

对于一般计算,您只需考虑图像行数/列数的额外一行。

x_offset = ( offset * rows ) // ( rows + 1 )

y_offset = ( offset * columns ) // ( columns + 1 )

换句话说:总偏移量除以总行数