在电商、广告或社交媒体中,我们经常看到商品图片带有光线扫过的动态效果,这类动效不仅吸引眼球,还能让产品显得更有质感。今天,我就分享一个用 Python 批量生成扫光 GIF 的小工具,并附带 可视化 GUI,操作非常简单。
技术栈与依赖
本工具使用了以下 Python 库:
Pillow:用于图片处理(读写、滤镜、透明通道等)。numpy:矩阵计算,加快图像运算。imageio:将图片序列生成 GIF。ttkbootstrap:美化版 Tkinter GUI,操作友好。tkinter:基础 GUI 框架,用于文件选择和交互。
安装依赖:
bash
pip install pillow numpy imageio ttkbootstrap
核心思路
-
生成光条 Mask 通过数学函数生成一个沿对角线扫过的光条掩码,并支持调节宽度、角度和多光源叠加效果。
-
叠加光条到原图 使用 NumPy 对图片像素做线性叠加,让光条有柔和的渐变效果,并支持调整亮度和透明度。
-
生成多帧 GIF 将每一帧的光条位置稍微移动,然后利用
imageio保存成 GIF,实现光条流动的效果。
关键代码示例
生成光条掩码
python
def make_sweep_mask(size, progress, offset=0.0, width_px=25):
W, H = size
diag = int((W**2 + H**2)**0.5 * 1.3)
x = np.linspace(-1.5, 1.5, diag)
y = np.linspace(-1.5, 1.5, diag)
xx, yy = np.meshgrid(x, y)
rad = np.deg2rad(35) # 光条角度
xr = xx * np.cos(rad) + yy * np.sin(rad)
center = progress * 2 - 1 + offset
dist = np.abs(xr - center)
mask = np.exp(-(dist / (width_px / min(W, H))) ** 2)
return Image.fromarray((mask * 255).astype(np.uint8), 'L').crop((diag-W)//2, (diag-H)//2, (diag+W)//2, (diag+H)//2)
光条叠加
python
def apply_sweep(base_img, frame_index, width_px=25):
mask = make_sweep_mask(base_img.size, frame_index / (FRAMES - 1), width_px=width_px)
mask = mask.filter(ImageFilter.GaussianBlur(max(1, int(min(base_img.size)*0.03))))
alpha = np.clip(np.array(mask)/255*1.5, 0, 1)
base_arr = np.array(base_img.convert("RGBA"), dtype=np.float32)
out_rgb = base_arr[..., :3] + alpha[..., None] * (255 - base_arr[..., :3])
return Image.fromarray(np.dstack([out_rgb, base_arr[...,3]]).astype(np.uint8), "RGBA")
批量生成 GIF
python
def generate_gif_batch():
file_paths = filedialog.askopenfilenames(title="选择图片")
output_dir = filedialog.askdirectory(title="选择输出文件夹")
for path in file_paths:
base = Image.open(path).convert("RGBA")
frames = [apply_sweep(base, i) for i in range(FRAMES)]
out_path = os.path.join(output_dir, os.path.splitext(os.path.basename(path))[0]+"_sweep.gif")
imageio.mimsave(out_path, frames, duration=float(duration_entry.get()))
GUI 使用界面
工具提供简单易用的 GUI:
- 输入光条宽度(px)
- 设置每帧时长(秒)
- 点击按钮选择多张图片并生成 GIF
GUI 使用 ttkbootstrap 美化,让操作更直观:
python
root = ttk.Window(title="扫光GIF生成器", themename="superhero")
width_entry = ttk.Entry(root)
duration_entry = ttk.Entry(root)
ttk.Button(root, text="生成 GIF", command=generate_gif_batch).pack()
root.mainloop()
效果展示
使用该工具,只需几秒钟就能将普通图片生成带光条扫过的动态 GIF,光条位置、宽度、透明度和帧数都可以灵活调节,非常适合电商主图和社交媒体动图。
总结
这个工具的特点:
- 批量处理:一次选择多张图片即可生成 GIF
- 可调光条:宽度、颜色、透明度、模糊可调
- GUI 操作简单:无需命令行即可完成全部操作
- 纯 Python 实现:跨平台、轻量级
如果你是电商运营或者社媒设计师,想给商品图片加点"亮点",这个小工具绝对值得一试。