PIL重复填充背景图像

4 投票
1 回答
5464 浏览
提问于 2025-04-18 09:23

我有一张小的背景图片,像这样:

在这里输入图片描述

这张图片比我需要的大小要小,所以我需要把它重复画上去。(可以想象成CSS里的background-repeat)

我搜索了很多,但还是找不到解决办法……非常感谢。

1 个回答

13

根据Marcin提供的代码,这段代码会在一个更大的背景上铺设一张背景图片:

from PIL import Image

# Opens an image
bg = Image.open("NOAHB.png")

# The width and height of the background tile
bg_w, bg_h = bg.size

# Creates a new empty image, RGB mode, and size 1000 by 1000
new_im = Image.new('RGB', (1000,1000))

# The width and height of the new image
w, h = new_im.size

# Iterate through a grid, to place the background tile
for i in xrange(0, w, bg_w):
    for j in xrange(0, h, bg_h):
        # Change brightness of the images, just to emphasise they are unique copies
        bg = Image.eval(bg, lambda x: x+(i+j)/1000)

        #paste the image at location i, j:
        new_im.paste(bg, (i, j))

new_im.show()

这样会产生如下效果:

1.png

如果去掉 Image.eval() 这一行,效果会变成:

2.png

撰写回答