daxigua
daxigua copied to clipboard
对改图圆形锯齿的优化
看到有人 @zhufree #13 贡献了批量改图的代码,我也是直接拿来用了,但是发现圆形锯齿比较明显,做了一点小小的优化:先画了一个很大的圆,然后缩放到应该大小,再蒙版剪裁。另外,也能支持jpg或者png的
# coding:utf-8
from PIL import Image, ImageDraw
import os
# 尺寸
size_dict = {
1: 52,
2: 80,
3: 108,
4: 119,
5: 152,
6: 183,
7: 193,
8: 258,
9: 308,
10: 308,
11: 408,
}
# 项目中的资源文件名
file_name_dict = {
1: 'ad/ad16ccdc-975e-4393-ae7b-8ac79c3795f2.png',
2: '0c/0cbb3dbb-2a85-42a5-be21-9839611e5af7.png',
3: 'd0/d0c676e4-0956-4a03-90af-fee028cfabe4.png',
4: '74/74237057-2880-4e1f-8a78-6d8ef00a1f5f.png',
5: '13/132ded82-3e39-4e2e-bc34-fc934870f84c.png',
6: '03/03c33f55-5932-4ff7-896b-814ba3a8edb8.png',
7: '66/665a0ec9-6c43-4858-974c-025514f2a0e7.png',
8: '84/84bc9d40-83d0-480c-b46a-3ef59e603e14.png',
9: '5f/5fa0264d-acbf-4a7b-8923-c106ec3b9215.png',
10: '56/564ba620-6a55-4cbe-a5a6-6fa3edd80151.png',
11: '50/5035266c-8df3-4236-8d82-a375e97a0d9c.png',
}
# 原图片文件夹,要求全部为正方形图片,1.png-11.png
raw_img_path = './love/'
# 项目中资源文件夹
des_img_path = './res/raw-assets/'
scale = 20
def circle(i):
w = size_dict[i]
radius = size_dict[i]//2
bigR = radius * scale
circle = Image.new('L', (bigR * 2, bigR * 2), 0) # 创建一个黑色背景的画布
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, bigR * 2, bigR * 2), fill=255) # 画白色圆形
try:
raw_img = Image.open(raw_img_path + str(i) + '.png')
except FileNotFoundError:
raw_img = Image.open(raw_img_path + str(i) + '.jpg')
avatar_size = (w, w)
circle = circle.resize(avatar_size, Image.ANTIALIAS)
im_resize = raw_img.resize(avatar_size, Image.ANTIALIAS)
alpha = Image.new('L', im_resize.size, 255)
alpha.paste(circle.crop((0, 0, radius, radius)), (0, 0)) # 左上角
alpha.paste(circle.crop((radius, 0, radius * 2, radius)),
(w - radius, 0)) # 右上角
alpha.paste(circle.crop((radius, radius, radius * 2, radius * 2)),
(w - radius, w - radius)) # 右下角
alpha.paste(circle.crop((0, radius, radius, radius * 2)),
(0, w - radius)) # 左下角
im_resize.putalpha(alpha)
im_resize.save(des_img_path + file_name_dict[i])
if __name__ == '__main__':
for i in range(1, 12):
circle(i)
哇,我也觉得锯齿很严重,太棒了