Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste in a specific place with Python PIL?

I am trying to create a program which takes 128 images of a balloon which their size is increasing in a fixed change, and paste each on different copy of a fixed image with a certain size, the image are bellow and also the code, the code that i have made until now is pasting them on the upper left of the image and i wand every picture to be pasted on the middle of the lower border of the copy, so the problem over all is with the area var creation: the background the balloon picture

from PIL import Image

i = 0

while(i < 128):
    balloon = Image.open("NEAREST" + str(i) + ".jpg")
    canvas = Image.open("blank.jpg")

    area = (0 ,0,298+i,298+i)
    canvas.paste(balloon, area)
    canvas.save("PASTE"+str(i)+".jpg")
    i = i + 1
like image 614
revolution Avatar asked Jul 11 '19 06:07

revolution


1 Answers

The area you set in .paste() is the position of the paste (left, top, right, bottom). Since you're setting left and top to zero, the balloon is pasted in the top left.

To paste it to the bottom middle, you have to calculate the correct values for the position:

The space on top is the height of the background minus the height of the pasted image, i.e. 425 - (298 + i), or just 425 - 298 - i or 127 - i

The space to the side is half of that to the top.

This gets you this code:

from PIL import Image

i = 0

while(i < 128):
    balloon = Image.open("NEAREST" + str(i) + ".jpg")
    canvas = Image.open("blank.jpg")

    space = 127 - i

    area = (int(space/2), space, int(space/2) + 298 + i, 425)
    canvas.paste(balloon, area)
    canvas.save("PASTE"+str(i)+".jpg")
    i = i + 1

Note that this is hard-coded to your situation, i.e. it only works if the background is 425x425 pixels. Otherwise you'd have to calculate it dynamically according to the image size.

like image 172
Serge Hauri Avatar answered Sep 18 '22 07:09

Serge Hauri