2011-03-09 22 views
13

我想使用PIL在Python中旋转图像并将expand参数设置为true。看起来,当我的图像背景为黑色时,保存为bmp的结果图像将比我的图像有白色背景的图像小很多,然后用白色展开替换黑色。在任何情况下,我的原始图像总是两种颜色,现在我需要的文件大小很小,因为我将这些图像放在嵌入式设备上。指定在Python中使用PIL旋转时的图像填充颜色并将扩展参数设置为true

任何想法,如果我可以强制旋转填充另一种颜色时扩大或如果有另一种方法来旋转我的照片,以使其变小?

回答

22

如果您的原始图像没有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') 
0

这是一个工作版本,受到答案的启发,但它的工作原理没有打开或保存图像,并显示如何旋转文本。

这两个图像具有彩色背景和不同于零的alpha通道以显示发生了什么。将两个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() 
相关问题