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

Ale*_*x B 16 python image colors rotation python-imaging-library

我正在尝试使用PIL在Python中旋转图像并将expand参数设置为true.似乎当我的图像背景为黑色时,保存为bmp的结果图像将比我的图像具有白色背景要小得多,然后我用白色替换黑色.在任何一种情况下,我的原始图像总是有两种颜色,现在我需要文件大小很小,因为我将这些图像放在嵌入式设备上.

任何想法,如果我可以强制旋转填充另一种颜色扩展或如果有另一种方式旋转我的图片,以使其小?

Pau*_*aul 30

如果原始图像没有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')
Run Code Online (Sandbox Code Playgroud)


Dei*_*eil 6

有一个参数,fillcolorrotate指定颜色,这将是使用了扩展区域的方法:

white = (255,255,255)
pil_image.rotate(angle, PIL.Image.NEAREST, expand = 1, fillcolor = white)
Run Code Online (Sandbox Code Playgroud)

https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.rotate