import os
from PIL import Image, ImageDraw, ImageFilter
from test_1.settings import BASE_DIR
def crop_max_square(pil_img):
return crop_center(pil_img, min(pil_img.size), min(pil_img.size))
def crop_center(pil_img, crop_width, crop_height):
img_width, img_height = pil_img.size
return pil_img.crop(((img_width - crop_width) // 2,
(img_height - crop_height) // 2,
(img_width + crop_width) // 2,
(img_height + crop_height) // 2))
def mask_circle_transparent(pil_img, blur_radius, offset=0):
offset = blur_radius * 2 + offset
mask = Image.new('L', pil_img.size, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((offset, offset, pil_img.size[0] - offset, pil_img.size[1] - offset), fill=255)
print((offset, offset, pil_img.size[0] - offset, pil_img.size[1] - offset))
mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))
result = pil_img.copy()
result.putalpha(mask)
return result
# 要自定义生成的logo
markImg = Image.open(os.path.join(BASE_DIR, 'data/pickel.png'))
thumb_width = 150
im_square = crop_max_square(markImg).resize((thumb_width, thumb_width), Image.LANCZOS)
im_thumb = mask_circle_transparent(im_square, 0)
# 底板
base_img = Image.open(os.path.join(BASE_DIR, '2.png')).convert('RGBA')
target = Image.new('RGBA', base_img.size, (0, 0, 0, 127))
# 圆形头像的大小
box = (125, 125, 315, 315)
region = im_thumb
region = region.convert("RGBA")
region = region.resize((box[2] - box[0], box[3] - box[1]))
x, y = region.size
target.paste(base_img, (0, 0))
# 合成地板 确定头像的圆心
target.paste(region, (120, 120), region)
target.save('demo.png')