tags:

views:

40

answers:

1

Trying to use pil for creating grid-like layout from images. 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
+2  A: 

Use itertools.product to iterate over the rows and columns:

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. I think the error in the code you posted is that you never reset 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.

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.

unutbu
Thank you. Actually the function is taking its variables from other functions, I removed them for clearing the question. That was my first question at stackoverflow.com, and I'm impressed :). Thank you again.
utdmr
@user472416: Welcome to stackoverflow! :)
unutbu