经常写博客,需要用到统一样式的文章封面,每次在ps制作都得搞半天,严重影响效率,于是写了这样一个小工具。
在当前目录下随机选择一张图片缩放大小为900*383,并对图片进行高斯模糊,最后加上在中心加上300*300的半透明正方形。
最后你就可以在ps或者其他编辑器里在中间的方块上写上你的文章标题了。
import os import random from PIL import Image from PIL import ImageDraw from PIL import ImageFilter # 获取当前目录下所有图片文件 files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith(('.png', '.jpg'))] # 随机选择一个图片文件 file = random.choice(files) # 打开图片并缩放 image = Image.open(file) image = image.resize((900, 383)) # 对图片进行高斯模糊 image = image.filter(ImageFilter.GaussianBlur(radius=5)) # 转换图片为 RGBA 格式 image = image.convert('RGBA') # 创建一个新的画布 canvas = Image.new('RGBA', (900, 383), (255, 255, 255, 0)) # 计算正方形的位置 x = (900 - 300) // 2 y = (383 - 300) // 2 # 在画布上绘制透明黑色正方形 black = (0, 0, 0, 128) canvas.paste(black, (x, y, x+300, y+300)) # 给正方形添加边框 width = 5 for i in range(width): draw = ImageDraw.Draw(canvas) draw.rectangle((x+i, y+i, x+300-i, y+300-i), outline=(255, 255, 255, 255)) # 合并图片 result = Image.alpha_composite(image, canvas) # 保存图片 if not os.path.exists('000'): os.makedirs('000') result.save(os.path.join('000', '1.png'))