使用PIL库将矩形图片转为原型图片
from PIL import Image, ImageDraw, ImageFilter
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)
mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))
result = pil_img.copy()
result.putalpha(mask)
return result
markImg = Image.open('./txIMG.jpg')
thumb_width = 150
im_square = crop_max_square(markImg).resize((thumb_width, thumb_width), Image.LANCZOS)
im_thumb = mask_circle_transparent(im_square, 0)
im_thumb.save('./txIMGCircle.png')
注意此段代码只能将jpg格式的图片转为圆形png格式,如果想转成圆形jpg格式的话则需要使用RGB转换,不过转过的效果并不怎么理想
效果图
这里在附上png转为jpg的示例代码
PNG to JPG