在Python中操作一组图像并将其放置在白色背景上

0 投票
1 回答
643 浏览
提问于 2025-04-17 20:34

我有一组图片(PNG格式),每张图片都有一些处理参数,比如缩放、旋转、以及在图像上的位置(x和y坐标)。我想把这些图片放到一张固定大小(但要足够大的)空白图片上,并且使用这些处理参数。

我觉得我可以用PIL这个库手动完成这些操作,但有些任务看起来有点复杂,比如旋转45度的时候,图片的某些部分可能会被裁掉。因此,我可能需要先把图片放到一个临时的更大尺寸的地方,然后再进行旋转,最后再把它放到最终的位置上。有没有什么好的例子或者库可以让这个过程更简单或者更直接呢?

1 个回答

1

这里有一个完整的例子,教你如何用pycairo创建一个背景图像,并在上面放置多个图片。这个例子部分参考了pyCairo: 如何调整和定位一张图片?,但增加了支持图片旋转的功能。

#!/usr/bin/python

# An example of how to create a background image and paste
# multiple images into it with pycairo.

import cairo
import math
import os

def pre_translate(ctx, tx, ty):
    """Translate a cairo context without taking into account its
    scale and rotation"""
    mat = ctx.get_matrix()
    ctx.set_matrix(cairo.Matrix(mat[0],mat[1],
                                mat[2],mat[3],
                                mat[4]+tx,mat[5]+ty))

def draw_image(ctx, image, centerX, centerY, height, width, angle=0):
    """Draw a scaled image on a given context."""
    image_surface = cairo.ImageSurface.create_from_png(image)

    # calculate proportional scaling
    img_height,img_width = (image_surface.get_height(),
                            image_surface.get_height())
    scale_xy = min(1.0*width/img_width,1.0*height / img_height)

    # scale, translate, and rotate the image around its center.
    ctx.save()
    ctx.rotate(angle)
    ctx.translate(-img_width/2*scale_xy,-img_height/2*scale_xy)

    ctx.scale(scale_xy, scale_xy)
    pre_translate(ctx, centerX, centerY)
    ctx.set_source_surface(image_surface)

    ctx.paint()
    ctx.restore()

width,height=512,512
surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, width, height)
cr = cairo.Context (surface)
pre_translate(cr, 0,0)

# Create the background
cr.rectangle(0,0,width,height)
cr.set_source_rgb(0,0,0.5)
cr.fill()

# Read an image
imagefile = 'tux.png'
if not os.path.exists(imagefile):
  import urllib
  urllib.urlretrieve('http://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png', imagefile)

for x in range(0,width,64):
    for y in range(0,height,64):
        angle = 1.0*(x+y)/(width+height-128)*2*math.pi
        draw_image(cr,
                   imagefile,
                   x+32,y+32,
                   64,64,
                   angle)

撰写回答