Ridoukei
Ridoukei

Reputation: 81

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

Upvotes: 8

Views: 19297

Answers (1)

Chris Henry
Chris Henry

Reputation: 416

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")

Upvotes: 12

Related Questions