243

I have a transparent png image foo.png and I've opened another image with:

im = Image.open("foo2.png")

Now what I need is to merge foo.png with foo2.png.

(foo.png contains some text and I want to print that text on foo2.png)

2
  • 103
    Don't use ; at the end of your commands in python: It's ugly...
    – nosklo
    Mar 16, 2011 at 11:48
  • Related question here
    – pjpscriv
    Oct 8, 2022 at 4:09

8 Answers 8

499
from PIL import Image

background = Image.open("test1.png")
foreground = Image.open("test2.png")

background.paste(foreground, (0, 0), foreground)
background.show()

First parameter to .paste() is the image to paste. Second are coordinates, and the secret sauce is the third parameter. It indicates a mask that will be used to paste the image. If you pass a image with transparency, then the alpha channel is used as mask.

Check the docs.

13
  • 16
    To make sure the foreground contains transparency in all cases, use foreground.convert('RGBA') for the mask parameter. Oct 4, 2012 at 2:28
  • 23
    I'm getting ValueError: bad transparency mask Mar 3, 2016 at 15:48
  • 1
    Depending on your version, you may have to install the Python Image Library, and:' from PIL import Image` Jul 23, 2016 at 17:57
  • 1
    Amazing, you can use image as mask. But can I use vectorial images like svg? Sep 14, 2016 at 1:57
  • 13
    @DenizOzger To fix ValueError: bad transparency mask use bg.paste(fg, (0, 0), fg.convert('RGBA')) Jan 1, 2019 at 3:01
100

Image.paste does not work as expected when the background image also contains transparency. You need to use real Alpha Compositing.

Pillow 2.0 contains an alpha_composite function that does this.

background = Image.open("test1.png")
foreground = Image.open("test2.png")

Image.alpha_composite(background, foreground).save("test3.png")

EDIT: Both images need to be of the type RGBA. So you need to call convert('RGBA') if they are paletted, etc.. If the background does not have an alpha channel, then you can use the regular paste method (which should be faster).

8
  • I just used paste() to overlay one semi-transparent image on another, with PIL, and it worked as I expected. In what way doesn't it work as you expected? Jul 25, 2013 at 17:27
  • 3
    @PeterHansen, paste() doesn't work as expected "when the background image also contains transparency".
    – homm
    Nov 5, 2014 at 17:19
  • 1
    @PeterHansen There is example: github.com/python-pillow/Pillow/issues/…
    – homm
    Nov 5, 2014 at 17:53
  • 4
    I get ValueError: image has wrong made as well @DenizOzger Oct 11, 2016 at 20:55
  • 2
    ValueError: images do not match . Because this method works only when the image sizes are same
    – Trect
    Nov 28, 2019 at 15:30
87

As olt already pointed out, Image.paste doesn't work properly, when source and destination both contain alpha.

Consider the following scenario:

Two test images, both contain alpha:

enter image description here enter image description here

layer1 = Image.open("layer1.png")
layer2 = Image.open("layer2.png")

Compositing image using Image.paste like so:

final1 = Image.new("RGBA", layer1.size)
final1.paste(layer1, (0,0), layer1)
final1.paste(layer2, (0,0), layer2)

produces the following image (the alpha part of the overlayed red pixels is completely taken from the 2nd layer. The pixels are not blended correctly):

enter image description here

Compositing image using Image.alpha_composite like so:

final2 = Image.new("RGBA", layer1.size)
final2 = Image.alpha_composite(final2, layer1)
final2 = Image.alpha_composite(final2, layer2)

produces the following (correct) image:

enter image description here

6
  • 4
    Thanks for the screenshots! Really helps!
    – Viet
    May 1, 2017 at 8:44
  • 1
    But alpha_composite can not set the offset, would you mind to give an example to completely replace paste function?
    – Mithril
    Jul 10, 2017 at 8:03
  • 3
    I guess you would have to create a new empty image with the same size as the garget image, paste the layer at the proper position and use alpha_compositing to blend the new image over the target image.
    – P.Melch
    Jul 11, 2017 at 15:24
  • 1
    I get: ValueError: images do not match
    – Student
    Jun 13, 2021 at 10:00
  • 2
    Images need to have the same size
    – P.Melch
    Jun 17, 2021 at 6:58
19

One can also use blending:

im1 = Image.open("im1.png")
im2 = Image.open("im2.png")
blended = Image.blend(im1, im2, alpha=0.5)
blended.save("blended.png")
5
  • 1
    This one ascetically worked for me. The images must have exactly the same size, but it is ok. The paste function did not quite cut it for me ...
    – Liviu Sosu
    Oct 4, 2017 at 11:42
  • 3
    'ValueError: images do not match'
    – Schütze
    Aug 8, 2018 at 5:50
  • 2
    Possibly, they are of different dimensions. You may need to scale or crop one of those.
    – nvd
    Aug 20, 2018 at 4:12
  • 2
    @Schütze see nvd's comment because he/she didn't ping (using @blahblah) you
    – MilkyWay90
    Mar 3, 2019 at 3:10
  • @Schütze I had to add these lines to avoid "images do not match": ` cloud_as_img.convert("RGBA") cloud_as_img.putalpha(255) cloud_as_img.save(temp_file_name) ` Mar 25, 2022 at 20:01
5

Here is my code to merge 2 images of different sizes, each with transparency and with offset:

from PIL import Image

background = Image.open('image1.png')
foreground = Image.open("image2.png")

x = background.size[0]//2
y = background.size[1]//2

background = Image.alpha_composite(
    Image.new("RGBA", background.size),
    background.convert('RGBA')
)

background.paste(
    foreground,
    (x, y),
    foreground
)

background.show()

This snippet is a mix of the previous answers, blending elements with offset while handling images with different sizes, each with transparency.

1
  • This answer doesn't appear to be quite correct. I've submitted an edit I think fixes it :)
    – pjpscriv
    Oct 8, 2022 at 3:47
3

Had a similar question and had difficulty finding an answer. The following function allows you to paste an image with a transparency parameter over another image at a specific offset.

import Image

def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
    fg_img_trans = Image.new("RGBA",fg_img.size)
    fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
    bg_img.paste(fg_img_trans,box,fg_img_trans)
    return bg_img

bg_img = Image.open("bg.png")
fg_img = Image.open("fg.png")
p = trans_paste(fg_img,bg_img,.7,(250,100))
p.show()
1
  • ValueError: images do not match May 15, 2019 at 14:33
2
def trans_paste(bg_img,fg_img,box=(0,0)):
    fg_img_trans = Image.new("RGBA",bg_img.size)
    fg_img_trans.paste(fg_img,box,mask=fg_img)
    new_img = Image.alpha_composite(bg_img,fg_img_trans)
    return new_img
1
  • 3
    Hi, can you possibly add a little more context to your answer? Otherwise the requestor is not likely to learn the "why" behind it.
    – jimf
    Apr 28, 2019 at 7:22
1

the key code is:

_, _, _, alpha = image_element_copy.split()
image_bg_copy.paste(image_element_copy, box=(x0, y0, x1, y1), mask=alpha)

the full function is:

def paste_image(image_bg, image_element, cx, cy, w, h, rotate=0, h_flip=False):
    image_bg_copy = image_bg.copy()
    image_element_copy = image_element.copy()

    image_element_copy = image_element_copy.resize(size=(w, h))
    if h_flip:
        image_element_copy = image_element_copy.transpose(Image.FLIP_LEFT_RIGHT)
    image_element_copy = image_element_copy.rotate(rotate, expand=True)
    _, _, _, alpha = image_element_copy.split()
    # image_element_copy's width and height will change after rotation
    w = image_element_copy.width
    h = image_element_copy.height
    x0 = cx - w // 2
    y0 = cy - h // 2
    x1 = x0 + w
    y1 = y0 + h
    image_bg_copy.paste(image_element_copy, box=(x0, y0, x1, y1), mask=alpha)
    return image_bg_copy

the above function supports:

  • position(cx, cy)
  • auto resize image_element to (w, h)
  • rotate image_element without cropping it
  • horizontal flip

Not the answer you're looking for? Browse other questions tagged or ask your own question.