Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when I use PIL to paste a crop to another image it raises ValueError

i am about to paste a little part of 2.jpg to 1.jpg

from PIL import Image
body = Image.open("1.jpg")
head = Image.open("2.jpg")
headbox = (0,0,30,30)

head.crop(headbox).save("head.jpg")
body.paste("head.jpg", (0,0)).save("out.jpg")

then it throw an error

  ****************************************, line 8, in <module>
    body.paste("head.jpg", (0,0)).save("out.jpg")
  File "C:\Users\liton\Anaconda3\lib\site-packages\PIL\Image.py", line 1401, in paste
    "cannot determine region size; use 4-item box"
ValueError: cannot determine region size; use 4-item box

I use pycharm and python 3.7 and I don't see any syntax error. so what's the matter with the code

like image 225
Ridoukei Avatar asked Mar 09 '19 13:03

Ridoukei


1 Answers

You should pass an image object to 'body.paste', however, you were just passing a string (image name). So first you need use open your image with 'Image.open' and then pass it to 'body.paste'. Also, 'body.paste' does not return any value so you cannot use the 'save' method directly. The following code will solve your issue:

from PIL import Image
body = Image.open("1.jpg")
head = Image.open("2.jpg")
headbox = (0,0,30,30)

head.crop(headbox).save("head.jpg")
head_crop = Image.open("./head.jpg")
body.paste(head_crop, (0,0))
body.save("out.jpg")
like image 64
Chris Henry Avatar answered Nov 15 '22 09:11

Chris Henry