5

I am trying to rotate image, but I want to maintain the size of the Image. For example in the following example image, I want to see a complete rectangle and have no black background color after rotating.

Please help me, I'd appreciate it.

Now my code is:

src_im = Image.open("test.gif")
im = src_im.rotate(30)
im.save("result.gif")

enter image description here enter image description here

stderr
  • 8,567
  • 1
  • 34
  • 50
Apple Wang
  • 245
  • 1
  • 6
  • 12

3 Answers3

3

try this one:

src_im = Image.open("test.jpg")
im = src_im.rotate(30,fillcolor='white', expand=True)
im.save("result.gif")

here comes the results:

test.jpg result.gif

Alpha
  • 668
  • 6
  • 11
2

To resize automatically, you want the expand kwarg:

src_im = Image.open("test.gif")
im = src_im.rotate(30, expand=True)
im.save("result.gif")

As the PIL docs explain:

The expand argument, if true, indicates that the output image should be made large enough to hold the rotated image. If omitted or false, the output image has the same size as the input image.

On the black background, you need to specify the transparent colour when saving your GIF image:

transparency = im.info['transparency'] 
im.save('icon.gif', transparency=transparency)
supervacuo
  • 9,072
  • 2
  • 44
  • 61
0

You havn't set the size of your new image - if you're only rotating by 30 degrees the image needs expanding...

From the http://effbot.org/imagingbook/image.htm page:

The expand argument, if true, indicates that the output image should be made large enough to hold the rotated image. If omitted or false, the output image has the same size as the input image.

So try (and this is typed into the browser so untested):

src_im = Image.open("test.gif")
im = src_im.rotate(30, expand=True)
im.save("result.gif")

For the black background thats a little more tricky- because you are rotating not by 90, there is an area of the square which needs to contain 'something' (although a transparancy might be what you want). Have a look at this answer: Specify image filling color when rotating in python with PIL and setting expand argument to true

Goodluck!

Community
  • 1
  • 1
mchicago
  • 121
  • 9