I'm trying to rotate an image in Python using PIL and having the expand argument to true. It seems that when the background of my image is black, the resulting image saved as a bmp will be a lot smaller than if I have a white background for my image, and then I replace the black due to expand with white. In either case, my original image is always of two colors, and right now i need the file size to be small, since I'm putting these images on an embedded device.
Any ideas if i can force rotate to fill in another color when expanding or if there is another way to rotate my picture in order to make it small?
PIL.Image.Image.rotate() method – This method is used to rotate a given image to the given number of degrees counter clockwise around its centre. Parameters: image_object: It is the real image which is to be rotated. angle: In degrees counter clockwise.
Python Imaging Library is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. It is available for Windows, Mac OS X and Linux. The latest version of PIL is 1.1.
To load the image, we simply import the image module from the pillow and call the Image. open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With