Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify image filling color when rotating in python with PIL and setting expand argument to true

Tags:

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?

like image 275
Alex B Avatar asked Mar 09 '11 21:03

Alex B


People also ask

How do you rotate an image in Python PIL?

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.

What is PIL image in Python?

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.

How do I import an image into Python using PIL?

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).


2 Answers

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') 
like image 55
Paul Avatar answered Sep 22 '22 19:09

Paul


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

like image 21
Deil Avatar answered Sep 20 '22 19:09

Deil