简体   繁体   English

Python-PIL-缺少图片

[英]Python - PIL - Missing images

Trying to use pil for creating grid-like layout from images. 尝试使用pil从图像创建类似网格的布局。 But that code only draws first column. 但是该代码仅绘制第一列。 Can anyone help me? 谁能帮我?

def draw(self):
    image=Image.new("RGB",((IMAGE_SIZE[0]+40)*5+40,(IMAGE_SIZE[1]+20)*CHILD_COUNT+20),(255,255,255))
    paste_x=(-1)*IMAGE_SIZE[0]
    paste_y=(-1)*IMAGE_SIZE[1]
    i=0
    for a range(5):
        paste_x=paste_x+IMAGE_SIZE[0]+40
        j=0
        for b in range(4):
            paste_y=paste_y+IMAGE_SIZE[1]+20
            image.paste(Image.new("RGB",IMAGE_SIZE,(0,0,0)),(paste_x,paste_y))
            j=j+1
        i=i+1    
    out=NamedTemporaryFile(delete=False)
    path=out.name
    image.save(out, "PNG")
    out.close()
    print path

Use itertools.product to iterate over the rows and columns: 使用itertools.product遍历行和列:

import tempfile
import Image
import itertools

COLUMNS=5
ROWS=5
VSEP=20
HSEP=40
IMAGE_SIZE=(100,100)

def draw():
    image=Image.new("RGB",
                    ((IMAGE_SIZE[0]+HSEP)*COLUMNS+HSEP,
                     (IMAGE_SIZE[1]+VSEP)*ROWS+VSEP),
                    (255,255,255))
    for row,column in itertools.product(range(ROWS),range(COLUMNS)):
        # print(row,column)  # uncomment this to see what itertools.product does
        paste_x=HSEP+column*(IMAGE_SIZE[0]+HSEP)
        paste_y=VSEP+row*(IMAGE_SIZE[1]+VSEP)
        image.paste(Image.new("RGB",IMAGE_SIZE,(0,0,0)),(paste_x,paste_y))
    out=tempfile.NamedTemporaryFile(delete=False)
    path=out.name
    image.save(out, "PNG")
    out.close()
    print path

draw()

Also, try not to use too many hard-coded numbers. 另外,请尽量不要使用太多的硬编码数字。 If you put the numbers in variables then your code is easier to change and it cuts down on potential errors. 如果将数字放在变量中,则代码更容易更改,并且可以减少潜在的错误。

PS. PS。 I think the error in the code you posted is that you never reset paste_y . 我认为您发布的代码中的错误是您永远不会重置paste_y After finishing the first column, the value of paste_y just keeps on growing, so you start pasting small images beyond the lower edge of the image . 在完成第一列后,价值paste_y只是不断增长,于是你开始粘贴小图片超越的下边缘image

So you could fix the problem by moving paste_y=-IMAGE_SIZE[1] to just after j=0 , but I still prefer doing it the way I show above. 因此,您可以通过将paste_y=-IMAGE_SIZE[1]移动到j=0 paste_y=-IMAGE_SIZE[1]解决问题,但我仍然更喜欢按照上面的显示方法进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM