PIL paste

A PIL Image object can paste another image onto itself.

Pasting an Image

Example: pasting a cat onto a canvas background.
The canvas pastes an image onto itself.

from PIL import Image
cat = Image.open('cat.jpg')
canvas = Image.open('bg.jpg')
canvas.paste(cat, (50, 100))
canvas.save('modified_canvas.png')

The Image.paste() function causes an object to modify itself.

It pastes the “cat” image object onto itself, with the top left corner of “cat” starting at (x,y) coordinates (50, 100).

This is unlike other functions like resize, crop, and convert which don’t modify the original object – those other ones actually return a new object. Paste does not return a new object.

You can see this in the code above if you notice that no new canvas object is created.

Pasting a colored rectangle:

canvas = Image.new("RGB", (200,200), "yellow")
canvas.paste("blue", (0,50,150,200))
canvas.save("new_canvas.png")

This example creates a new “canvas” object with yellow coloring in every pixel.
Then the canvas pastes a blue rectangle onto itself.

When you paste a color instead of an image object, you need to give it four coordinates (x1, y1, x2, y2). These define the top left and bottom right corners of a rectangle. (only two coordinates were needed when pasting a picture – just the (x,y) of the top left corner.)

Pasting Tips:

  • Use the resize() function to make the picture you’re pasting any size you like.
  • Use the crop() function to remove stuff you don’t want to paste.
  • Use the new() function to create a background image that’s the right size.