1

So recently I came across a little issue while writing a Python library, involving the rotation of images with PIL.

I was trying to rotate an image I was loading by calling Image#rotate(angle, expand=True) on an image would create weird black bars around the image:

image = Image.open('image.png')
image = image.rotate(angle, expand=True)

Rotated Image with Black Bars/Excess

This is obviously not ideal for us as we want the image rotated without any sort of additions or excess. This is obviously not what we wanted.

In terms of answers, you find a lot of suggestions to set the fillcolor argument on the rotate method.

image.rotate(angle, expand=True, fillcolor=(0, 0, 0, 0))

It's clear that this looks like it could be a solution but the fillcolor cannot be RGBA, so we cannot pass in an alpha value.

martineau
  • 119,623
  • 25
  • 170
  • 301
FeaturedSpace
  • 479
  • 3
  • 18
  • Related to, and solved below for: https://stackoverflow.com/questions/5252170/specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand https://stackoverflow.com/questions/11937985/how-to-use-pil-python-image-library-rotate-image-and-let-black-background-to/11938647 https://stackoverflow.com/questions/56765467/is-there-another-way-to-fill-the-area-outside-a-rotated-image-with-white-color – FeaturedSpace Feb 16 '21 at 22:19

1 Answers1

2

The proper answer to this is to ensure your image is in the correct mode. Even if you load an image that supports transparency (such as a .png), you will still encounter this error unless you convert the image mode from its default to 'RGBA', like so:

image = Image.open('image.png').convert('RGBA')

Which then allows the rotation to be completely scuff-free!

enter image description here

I decided to post this question/answer combo because I searched for hours to find this answer, and I thought I'd make it more accessible to anybody else who experiences my issue!

Here's where I found the answer, on an old forum from long, long ago:

    rotate image with transparent background?

martineau
  • 119,623
  • 25
  • 170
  • 301
FeaturedSpace
  • 479
  • 3
  • 18