使用PIL在python中旋转并将expand参数设置为tru时指定图像填充颜色

2024-04-25 05:44:26 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
2条回答

这是一个工作版本,灵感来自答案,但它没有打开或保存图像和演示如何旋转文本的工作。

这两张图片的背景颜色和alpha通道与0不同,以显示发生了什么。将两个alpha通道从92更改为0将使它们完全透明。

from PIL import Image, ImageFont, ImageDraw

text = 'TEST'
font = ImageFont.truetype(r'C:\Windows\Fonts\Arial.ttf', 50)
width, height = font.getsize(text)

image1 = Image.new('RGBA', (200, 150), (0, 128, 0, 92))
draw1 = ImageDraw.Draw(image1)
draw1.text((0, 0), text=text, font=font, fill=(255, 128, 0))

image2 = Image.new('RGBA', (width, height), (0, 0, 128, 92))
draw2 = ImageDraw.Draw(image2)
draw2.text((0, 0), text=text, font=font, fill=(0, 255, 128))

image2 = image2.rotate(30, expand=1)

px, py = 10, 10
sx, sy = image2.size
image1.paste(image2, (px, py, px + sx, py + sy), image2)

image1.show()

如果原始图像没有alpha层,则可以使用alpha层作为遮罩将背景转换为白色。当rotate创建“背景”时,它使其完全透明。

# original image
img = Image.open('test.png')
# converted to have an alpha layer
im2 = img.convert('RGBA')
# rotated image
rot = im2.rotate(22.2, expand=1)
# a white image same size as rotated image
fff = Image.new('RGBA', rot.size, (255,)*4)
# create a composite image using the alpha layer of rot as a mask
out = Image.composite(rot, fff, rot)
# save your work (converting back to mode='1' or whatever..)
out.convert(img.mode).save('test2.bmp')

相关问题 更多 >