Apple  Wang
Apple Wang

Reputation: 245

Python Django how to rotate image and remove black color?

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

Upvotes: 5

Views: 3520

Answers (3)

Alpha
Alpha

Reputation: 715

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

Upvotes: 3

supervacuo
supervacuo

Reputation: 9262

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)

Upvotes: 2

mchicago
mchicago

Reputation: 121

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!

Upvotes: 0

Related Questions