python裁剪圆形图片抗锯齿

用python将一张图片裁剪成圆形,是很简单的。但是有个最大的问题就是总是出现锯齿。今天在Stack Overflow上搜了一下,果然有大神解决了这个问题。我看了一下源码,然后自己修改了一下,能够直接将一张图片,裁剪成圆形抗锯齿的图片。

对比如下两张图片即可看出区别:
-w300-w300

Stack Overflow的地址在此:
https://stackoverflow.com/questions/32504246/draw-ellipse-in-python-pil-with-line-thickness

修改之后的代码在此:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import os, math
import sys
from PIL import Image, ImageDraw


def draw_ellipse(image, bounds, width=1, outline='white', antialias=4):
"""Improved ellipse drawing function, based on PIL.ImageDraw."""

# Use a single channel image (mode='L') as mask.
# The size of the mask can be increased relative to the imput image
# to get smoother looking results.
mask = Image.new(
size=[int(dim * antialias) for dim in image.size],
mode='L', color='black')
draw = ImageDraw.Draw(mask)

# draw outer shape in white (color) and inner shape in black (transparent)
for offset, fill in (width/-2.0, 'black'), (width/2.0, 'white'):
left, top = [(value + offset) * antialias for value in bounds[:2]]
right, bottom = [(value - offset) * antialias for value in bounds[2:]]
draw.ellipse([left, top, right, bottom], fill=fill)

# downsample the mask using PIL.Image.LANCZOS
# (a high-quality downsampling filter).
mask = mask.resize(image.size, Image.LANCZOS)

# paste outline color to input image through the mask
image.putalpha(mask)

#
def circle_new(fileName,finaleName):
ima = Image.open(fileName).convert("RGBA")
size = ima.size
r2 = min(size[0], size[1])
if size[0] != size[1]:
ima = ima.resize((r2, r2), Image.ANTIALIAS)
ellipse_box = [0,0,r2-2,r2-2]
draw_ellipse(ima, ellipse_box, width=1)

ima.save('%s.png' % finaleName)

dirName= sys.argv[1]
imgCount = 0
for root,dirNames,fileNames in os.walk(dirName):
for fileName in fileNames:
if fileName.split(".")[-1] in ["jpg","png"]:
fileFullPath = os.path.join(root,fileName)
circle_new(fileFullPath,imgCount)
# os.rename(fileFullPath,str(imgCount) + "." + fileName.split(".")[-1])
imgCount += 1