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

查看:337
本文介绍了如何在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实例的粘贴方法:

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技巧可以在纳迪亚Alramli的PIL教程

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

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

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