Specify image filling color when rotating in python with PIL and setting expand argument to true
If your original image has no alpha layer, you can use an alpha layer as a mask to convert the background to white. When rotate
creates the "background", it makes it fully transparent.
# 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')
There is a parameter fillcolor
in a rotate
method to specify color which will be use for expanded area:
white = (255,255,255)
pil_image.rotate(angle, PIL.Image.NEAREST, expand = 1, fillcolor = white)
https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.rotate