How do you composite an image onto another image with PIL in Python?

后端 未结 5 1550
忘了有多久
忘了有多久 2020-12-07 14:19

I need to take an image and place it onto a new, generated white background in order for it to be converted into a downloadable desktop wallpaper. So the process would go:

5条回答
  •  鱼传尺愫
    2020-12-07 14:54

    This can be accomplished with an Image instance's paste method:

    from PIL import Image
    img = Image.open('/path/to/file', 'r')
    img_w, img_h = img.size
    background = Image.new('RGBA', (1440, 900), (255, 255, 255, 255))
    bg_w, bg_h = background.size
    offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)
    background.paste(img, offset)
    background.save('out.png')
    

    This and many other PIL tricks can be picked up at Nadia Alramli's PIL Tutorial

提交回复
热议问题