PIL - 从JPG和PNG帧生成一个PNG

2 投票
1 回答
2258 浏览
提问于 2025-04-17 09:12

我有两张图片:

  • 一张PNG格式的图片(99x97),有一个白色的旋转框,其他地方都是透明的。
  • 一张JPG格式的缩略图(80x80),是我生成的。

现在我想把缩略图放到框里面,让它看起来像一幅画。该怎么做呢?

补充说明:

我忘了说,图片必须放在框的下面。

框的图片

我有一些代码,但它只显示了框,里面没有图片 :/

import Image, ImageDraw

img_size = (99,97)
im = Image.open('logo.jpg')
picture = im.crop((0,0,80,80))
frame = Image.open('thumb-frame.png')
picture = picture.convert('RGBA')
background = Image.new('RGBA', img_size, (255, 255, 255, 0))
background.paste(picture, (10,9))
background.paste(frame, (0,0))
background.save('logocopy.png', 'PNG')

补充说明:

问题解决了。我需要在.paste()中添加透明度遮罩。

import Image

im = Image.open('logo.jpg')
picture = im.crop((0,0,80,80))
picture = picture.convert('RGBA')
frame = Image.open('thumb-frame.png')
background = Image.new('RGBA', frame.size, (255, 255, 255, 0))
background.paste(picture, (10,9))
background.paste(frame, (0,0), frame)
background.save('logocopy.png', 'PNG')

1 个回答

0

这里是你需要的。这段代码会把原始图片拿出来,然后在上面贴上一个透明的框架图片。两张图片的大小都是100x100,但你可以根据需要调整大小。

from PIL import Image

frame = Image.open('frame.png')
img = Image.open('image.jpg')

img_dest = img.copy().convert('RGBA')
img_dest.paste(frame, (0, 0, 100, 100), frame)

img_dest = img_dest.convert('RGB') # Optional, to remove transparency info

img_dest.save('output.png')

撰写回答