mercredi 5 mai 2021

Repeat the random combination of images using loop and insert them in A4 format correctly

I'm trying to make this short script work which randomly overlays 3 different images (see the images link below). It would have to loop N times and then assemble them at the end into a single image of (possibly) A4 size. I've tried different combinations several times but I'm confused and can't get the loop to work properly (the images are all identical copies of the first one and paste proceeding on the right) neither fit the images in A4 format. Any help really really appreciated!

(note:I've removed the snippet of A4 code because it was just messing up the script)

[url=https://postimg.cc/SXsvXSqV][img]https://i.postimg.cc/SXsvXSqV/background2.png[/img][/url]

[url=https://postimages.org/][img]https://i.postimg.cc/FfBn3MHv/orangedot.png[/img][/url]

[url=https://postimg.cc/k6RYcT2b][img]https://i.postimg.cc/k6RYcT2b/whiteX.png[/img][/url]

wrong result:

out.png (https://postimg.cc/TLym5SpZ)

from PIL import Image
import random

#bckgnd = 200x200
#whiteX = 200x200
#orangedot = 30x30

bckgnd = Image.open('background2.png').convert('RGBA')  # Convert to mode supporting alpha.

orangedot = Image.open('orangedot.png')
orangedot_x, orangedot_y = random.randint(30, 170), random.randint(0, 100)
tmp_img = Image.new('RGBA', bckgnd.size, color=(0, 0, 0, 0))
tmp_img.paste(orangedot, (orangedot_x, orangedot_y))
bckgnd.alpha_composite(tmp_img)

whiteX = Image.open('whiteX.png')
tmp_img = Image.new('RGBA', bckgnd.size, color=(0, 0, 0, 0))
tmp_img.paste(whiteX)  # Assumes it's the same size as background image.
bckgnd.alpha_composite(tmp_img)



bckgnd.save("test.png")
bckgnd.show()


img_to_paste = Image.open('test.png')
width, height = img_to_paste.size

n = 20  # paste image n-times

img = Image.new('RGBA', (width * n, height), color=(0, 0, 0, 0))  # set width, height of new image
img.save('out.png')

for i in range(0, n):
    out = Image.open('out.png')
    out.paste(img_to_paste, (i * width, 0))  # the second argument here is tuple representing upper left corner
    out.save('out.png')

#img.show()




Aucun commentaire:

Enregistrer un commentaire