原图如下:
1.jpg
结果图:
2.png
代码:
from PIL import Image, ImageDraw
def picture_turns_round(image, diameter_scale=1):
"""
将图片转为圆形
:param image:图片
:param diameter_scale: 圆形直径与image最短边的比例
:return:
"""
radius = int(diameter_scale * min(image.size) / 2)
rgbm = image.split()
if len(rgbm) == 4:
r, g, b, mask = rgbm
else:
r, g, b = rgbm
mask = Image.new('L', image.size, 0)
mask_draw = ImageDraw.Draw(mask)
w, h = image.size
w_, h_ = int(w / 2), int(h / 2)
xy = ((w_ - radius, h_ - radius), (w_ + radius, h_ + radius))
mask_draw.ellipse(xy, fill=255)
return Image.merge('RGBA', (r, g, b, mask))
if __name__ == "__main__":
img = Image.open('cat.jpg')
round_img = picture_turns_round(img)
round_img.show()
使用时若提示PIL
没有安装,可以使用pip instal Image
来安装
网友评论