Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The easiest way to do it is by using masks. Create a black and white mask with any shape you want. And put that shape as an alpha layer </p> <pre><code>from PIL import Image, ImageOps mask = Image.open('mask.png').convert('L') im = Image.open('image.png') output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.putalpha(mask) output.save('output.png') </code></pre> <p>Here is the mask I used</p> <p><img src="https://imgur.com/d57og.png" alt="alt text"></p> <hr> <p>If you want the thumbnail size to be variable you can use the ImageDraw and draw the mask.</p> <pre><code>from PIL import Image, ImageOps, ImageDraw size = (128, 128) mask = Image.new('L', size, 0) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + size, fill=255) im = Image.open('image.jpg') output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.putalpha(mask) output.save('output.png') </code></pre> <hr> <p>If you want the output in GIF then you need to use the paste function instead of putalpha:</p> <pre><code>from PIL import Image, ImageOps, ImageDraw size = (128, 128) mask = Image.new('L', size, 255) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + size, fill=0) im = Image.open('image.jpg') output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.paste(0, mask=mask) output.convert('P', palette=Image.ADAPTIVE) output.save('output.gif', transparency=0) </code></pre> <p>Note that I did the following changes:</p> <ul> <li>The mask is now inverted. The white was replace with black and vis-versa.</li> <li>I'm converting into 'P' with an 'adaptive' palette. Otherwise PIL will only use web-safe colors and the result will look bad.</li> <li>I'm adding transparency info with to the image</li> </ul> <p><strong>Please note</strong>: There is a big issue with this approach. If the gif image contained black parts, all of them will become transparent as well. You can work around this by choosing another color for the transparency. I would strongly advice you to use PNG format for this. But if you can't then that is the best you could do. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload