白色转透明,根据颜色值来判断,将符合条件的像素值alpha通道值改为0
from PIL import Image
def transPNG(srcImageName,dstImageName):
img = Image.open(srcImageName)
img = img.convert("RGBA")
datas = img.getdata()
newData = list()
for item in datas:
if item[0] >250 and item[1] > 250 and item[2] > 250:
newData.append(( 255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
img.save(dstImageName,"PNG")
transPNG("a0.png","aa0.png")
gif动图修改
from PIL import Image, ImageDraw, ImageFont
import imageio,os,sys
def Gif2PNG():
def processImage(infile):
try:
im = Image.open(infile)
except IOError:
print ("Cant load", infile)
sys.exit(1)
i = 0
mypalette = im.getpalette()
try:
while 1:
im.putpalette(mypalette)
new_im = Image.new("RGBA", im.size)
new_im.paste(im)
new_im.save('a'+str(i)+'.png')
i += 1
im.seek(im.tell() + 1)
except EOFError:
pass
processImage('source.gif')
def NewNameImg(name='测试',size=(63, 22),axis=(2, 2),fontsize=22):
'''创建名字图片 name 名字 size 图片尺寸 axis 文字定位坐标 fontsize 字体大小'''
image = Image.new('RGBA', size, (255,255,255))
draw = ImageDraw.Draw(image)
setFont = ImageFont.truetype('C:/windows/fonts/simhei.ttf', fontsize)
fillColor = "#000000"
draw.text(axis, name, font=setFont, fill=fillColor)
return image
def newGif(name='测试',axis=(81,118),duration=0.1, outName='gif.gif'):
'''创建GIF name 名字 axis 名字放的位置 duration 动画间隔 outName 输出名字'''
img2=NewNameImg(name,size=(172,24))
images = []
filenames=sorted((fn for fn in os.listdir('.') if fn.endswith('.png')))
for filename in filenames:
img=Image.open(filename)
img.paste(img2, axis)
img.save(filename)
images.append(imageio.imread(filename))
imageio.mimsave(outName, images,duration=duration)
if __name__ == '__main__':
newGif('测试',axis=(9,152), duration=0.05)