我将使用Python和Pillow库批量编辑.png文件。这是我第一个用Python编写脚本,因此很可能存在许多错误和/或不良编程实践。
以下是我的当前代码:
我的目标是使无生命的蛋图像最终像下面显示的动画图像一样:
我代码中的问题首先在于,从第35行到第47行的整个部分导致透明度丢失(这是由于第47行造成的)。而我不知道如何将列表(图像)转换为动态GIF。
以下是我的当前代码:
from PIL import Image
from PIL import ImageDraw
from os.path import basename
import os, sys
path = "D:\Pokemon Game\Pokemon Eggs\Import"
dirs = os.listdir( path )
box = (2,1,30,31)
moveup = (0, -3, -7, -11, -15, -19, -15, -9, -5, 2, 12, 14, 16, 17, 12, 8, 4, 0, -7, -13, -19, -11, -7, -5, -3)
topspace = (36, 38, 42, 46, 50, 55, 50, 44, 40, 34, 24, 22, 20, 18, 24, 28, 32, 36, 42, 48, 55, 46, 42, 40, 38)
bottomspace = (0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 10, 14, 17, 12, 8, 4, 0, 0, 0, 0, 0, 0, 0, 0)
Imagesizes = ((56, 60), (56, 58), (56, 54), (56, 50), (56, 46), (56, 41), (56, 46), (56, 52), (56, 56), (56, 60), (56, 66), (56, 64), (56, 62), (56, 60), (56, 60), (56, 60), (56, 60), (56, 60), (56, 54), (56, 48), (56, 41), (56, 50), (56, 54), (56, 56), (56, 58))
for file in dirs:
#Pick an image file you have in the working directory
egg = Image.open("D:\Pokemon Game\Pokemon Eggs\Import\%s" % str(file))
#Crops white out of image
egg = egg.crop(box)
#Resizes image
egg = egg.resize((56, 60), Image.NEAREST)
#Stretch individual images
frames = []
for size in Imagesizes:
frames.append(egg.resize(size, Image.NEAREST))
#Resize canvas for each individual image - make sure it is clear
for i,image in enumerate(frames):
canvassize = (-20, -36 + moveup[i], 76, 60 + moveup[i])
frames[i]=image.crop(canvassize)
#Fix transparency
for i,image in enumerate(frames):
transparent_area1 = (0,0,20,96)
transparent_area2 = (76,0,96,96)
transparent_area3 = (0,0,96,(topspace[i]))
transparent_area4 = (0,(96-bottomspace[i]), 96, 96)
image.convert('RGBA')
mask=Image.new("1", (96, 96), color=255)
draw=ImageDraw.Draw(mask)
draw.rectangle(transparent_area1, fill=0)
draw.rectangle(transparent_area2, fill=0)
draw.rectangle(transparent_area3, fill=0)
draw.rectangle(transparent_area4, fill=0)
image.putalpha(mask)
#Convert to GIF
我的目标是使无生命的蛋图像最终像下面显示的动画图像一样:
![http://i.imgur.com/NACaqCI.png](https://istack.dev59.com/nDNdA.webp)
![http://imgur.com/a/xYAq9](https://istack.dev59.com/4daHl.gif)