如何在 Python 中使用 PIL 将图像合成到另一个图像上? [英] How do you composite an image onto another image with PIL in Python?

查看:85
本文介绍了如何在 Python 中使用 PIL 将图像合成到另一个图像上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要拍摄一张图片并将其放置在新生成的白色背景上,以便将其转换为可下载的桌面墙纸.所以这个过程会进行:

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:

  1. 生成尺寸为 1440x900 的新的全白图像
  2. 将现有图像放在顶部,居中
  3. 另存为单张图片

在 PIL 中,我看到了 ImageDraw 对象,但没有任何迹象表明它可以将现有的图像数据绘制到另一个图像上.任何人都可以推荐的建议或链接?

In PIL, I see the ImageDraw object, but nothing indicates it can draw existing image data onto another image. Suggestions or links anyone can recommend?

推荐答案

这可以通过 Image 实例的 paste 方法来完成:

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')

这个和许多其他 PIL 技巧可以在 Nadia Alramli 的 PIL 教程

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

这篇关于如何在 Python 中使用 PIL 将图像合成到另一个图像上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆