How to crop from one image and paste into another using PIL

Hey guys. This has probably been asked a million times, but I have a little problem here. With PIL, I am trying to copy a rectangle from an image and paste it into another. This is my code.

import Image ii = Image.open("ramza.png") box = (70, 70, 30, 30) region = ii.crop(box) io = Image.open("template.png") io.paste(region, box) io.save("output.png") 

And I get this error:

ValueError: images do not match

Do any of you know about this?

+7
source share
2 answers

The PIL cropping field is defined as the 4-element pixel coordinates: (left, upper, right, lower) .

To fix your code to get a 30x30 crop:

 box = (70, 70, 100, 100) 

It is broken into components:

 x, y, w, h = (70, 70, 30, 30) box = (x, y, x + w, y + h) 
+11
source

For future visitors, this error can also occur if the box argument for paste contains a float instead of int s.

+2
source

All Articles