重复填充背景图像

2024-03-28 12:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的小背景图像:

enter image description here

它比我的图像尺寸小,所以我需要反复画。(想想css中的背景重复)

我找了很多东西都找不到解决办法……非常感谢。在


Tags: 图像尺寸css背景解决办法
1条回答
网友
1楼 · 发布于 2024-03-28 12:30:40

根据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

相关问题 更多 >