0

I wanted to merge three images using PIL in python. I have spent a while trying to get three images to merge, but I am able to merge two.

I am aware of the question that was asked about merging two images (How to merge a transparent png image with another image using PIL)

Here is my code:

def addImageList(imageNameList):
    ((Image.open(imageNameList[0]).paste(Image.open(imageNameList[1]), (0, 0),
      Image.open(imageNameList[1]))).paste(Image.open(imageNameList[2]), (0, 0),
      Image.open(imageNameList[2]))).show()

When this runs, I get the error: AttributeError: 'NoneType' object has no attribute 'paste'

I have tried merging only two of the pictures, and that worked well.

martineau
  • 119,623
  • 25
  • 170
  • 301
Ajy_Chikn
  • 3
  • 3

1 Answers1

0

Image.paste returns None, for the same reason that list.sort does. You are not creating a new image, you are modifying an existing one. In Python, the default expectation is that the interface is not "fluent" when the code depends on side effects.

Even when it works, trying to do everything in a single step just makes the code more complicated. It's much easier to read when the Image.open calls happen ahead of time - that also avoids repeating those calls. Also, code like this doesn't naturally extend if you want the list of image names to contain more names.

Just do things one step at a time. We can use a simple loop to iterate over the image names after the first one. (Please also note the standard Python naming conventions.)

def compose_images(image_names):
    bg_name, *other_names = image_names
    image = Image.open(bg_name)
    for fg_name in other_names:
        foreground = Image.open(fg_name)
        image.paste(foreground, (0, 0), foreground)
    image.show()
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    Since you're being so pedantic, note that `Image.open()` returns a context manager (see [File Handling in Pillow](https://pillow.readthedocs.io/en/latest/reference/open_files.html#file-handling)) so it can be used with a `with` statement. – martineau Jan 08 '22 at 02:34