我已经安装了Pillow 2.4.0(在OS X虚拟环境和Ubuntu 14.04 EC2上)。我编写了以下脚本以生成波形可视化图形(从Jiaaro获取灵感)。它使用Pydub库分析波形,并使用PIL/Pillow的ImageDraw函数绘制线条。wav变量是一个audiosegment()(来自Pydub库),imgname是一个字符串:
def draw_waveform(wav, imgname, color="#000000", w=400, h=40):
sound = wav
name = imgname
width = w
height = h
color = color
chunk_length = len(sound) / width
loudness_of_chunks = [
sound[ i*chunk_length : (i+1)*chunk_length ].rms
for i in range(width)]
max_rms = max(loudness_of_chunks)
scale = max_rms/(height/2)
size = (width,height)
im = Image.new('RGBA', size, (255, 255, 255, 255))
draw = ImageDraw.Draw(im)
for i in range(1, width):
pos = (width - i, height/2 + loudness_of_chunks[i]/scale-4)
draw.line((width - i,height/2) + pos, fill=color)
pos = (width - i, height/2 - loudness_of_chunks[i]/scale+4)
draw.line((width - i,height/2) + pos, fill=color)
del draw
im.rotate(180).save(app.config['UPLOAD_FOLDER'] + '/' + name, 'GIF', transparency=0) #, transparency=0
return app.config['UPLOAD_FOLDER'] + '/' + name
所有的都很棒,大部分时间都是这样。在某些波形上,特别是那些最接近峰值的波形上,PIL会输出一个带有翻转透明度的GIF - 波形将是透明的,周围的空间将是白色的。通常情况下,背景是透明的,波形是黑色的(#000000)。
以下是预期输出的图片:
我能为您提供帮助,以下是需要翻译的内容:
而不正确的(右键另存为并在图像编辑器中打开,因为其背景是白色的,中间是透明的):
有人遇到类似的问题吗?我是否漏掉了一些显而易见的东西(很可能是)?
'P'
代替'RGBA'
,并在save
上设置透明索引。请参阅http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html#gif - Mark Ransom