Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL's Image.rotate() crops image

I am trying out the Python Imaging Library, but `Image.rotate() seems to crop the image:

from PIL import Image 
fn='screen.png'
im = Image.open(fn)
im = im.rotate(-90)
im = im.rotate(90)
im.show()
im.save('cropped.png')

The original image screen.png is:

enter image description here

The cropped image cropped.png is:

enter image description here

The cropping is caused by the 1st rotation and retained in the 2nd rotation.

I am still new to Python, despite trying to become more familiar with it over the years. Is this me doing something wrong with the PIL or is it a bug?

My Python version is:

Python 3.8.8 (default, Mar  4 2021, 21:24:42) 
[GCC 10.2.0] on cygwin
like image 545
user36800 Avatar asked Nov 16 '25 07:11

user36800


1 Answers

Thanks to pippo1980, the solution is to specify expand=1 when invoking rotate():

from PIL import Image 
fn='screen.png'
im = Image.open(fn)
im = im.rotate(-90,expand=1)
im = im.rotate(90,expand=1)
im.show()
im.save('cropped.png')

It adjusts the "outer image" width and height to allow an arbitrarily rotated image to fit without cropping. Despite the name, it also shrinks width/height where appropriate.

like image 165
user36800 Avatar answered Nov 17 '25 19:11

user36800