如何在Python中用PIL将一张图片合成到另一张上?

115 投票
6 回答
138050 浏览
提问于 2025-04-15 21:08

我需要把一张图片放到一个新的白色背景上,这样就可以把它转换成可以下载的桌面壁纸。整个过程大致是这样的:

  1. 生成一张全白的图片,尺寸为1440x900
  2. 把已有的图片放在上面,居中对齐
  3. 保存为一张完整的图片

在PIL库中,我看到有一个ImageDraw对象,但没有什么说明它可以把已有的图片数据画到另一张图片上。有没有人能推荐一些建议或链接呢?

6 个回答

5

这是为了做类似的事情

我开始的时候是在Photoshop里生成了一个“白色背景”,然后把它导出为PNG文件。这就是我得到的im1(图像1)。接着我用了粘贴功能,因为这样更简单。

from PIL import Image

im1 = Image.open('image/path/1.png')
im2 = Image.open('image/path/2.png')
area = (40, 1345, 551, 1625)  
im1.paste(im2, area)
                   l>(511+40) l>(280+1345)
         |    l> From 0 (move, 1345px down) 
          -> From 0 (top left, move 40 pixels right)

那么这些数字是怎么来的呢? (40, 1345, 551, 1625) im2.size (511, 280) 因为我在右边加了40,下边加了1345(40, 1345, 511, 280),所以我必须把它们加到原始图像的大小上,这样就得到了(40, 1345, 551, 1625)

im1.show() 

来展示你的新图像

9

根据unutbus的回答:

#!/usr/bin/env python

from PIL import Image
import math


def resize_canvas(old_image_path="314.jpg", new_image_path="save.jpg",
                  canvas_width=500, canvas_height=500):
    """
    Place one image on another image.

    Resize the canvas of old_image_path and store the new image in
    new_image_path. Center the image on the new canvas.
    """
    im = Image.open(old_image_path)
    old_width, old_height = im.size

    # Center the image
    x1 = int(math.floor((canvas_width - old_width) / 2))
    y1 = int(math.floor((canvas_height - old_height) / 2))

    mode = im.mode
    if len(mode) == 1:  # L, 1
        new_background = (255)
    if len(mode) == 3:  # RGB
        new_background = (255, 255, 255)
    if len(mode) == 4:  # RGBA, CMYK
        new_background = (255, 255, 255, 255)

    newImage = Image.new(mode, (canvas_width, canvas_height), new_background)
    newImage.paste(im, (x1, y1, x1 + old_width, y1 + old_height))
    newImage.save(new_image_path)

resize_canvas()

记得使用Pillow库(文档, GitHub, PyPI),而不是python-imaging,因为Pillow可以在Python 2.X和Python 3.X上使用。

189

这可以通过图像实例的 paste 方法来实现:

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

你可以在 Nadia Alramli的PIL教程 中找到这个和其他很多PIL的技巧。

撰写回答