Python Mutagen:通过网址添加封面照片/专辑封面?

时间:2014-04-25 19:18:01

标签: python python-imaging-library urllib pillow mutagen

使用mutagen,我可以添加titleartistgenre等常规元标记,但是当我尝试通过网址添加图片时,它并没有。工作。

from mutagen.mp4 import MP4
from mutagen.mp4 import MP4Cover
from PIL import Image
import urllib2 as urllib
import io, sys, getopt

#url is defined elsewhere
audio = MP4(url)
#clear previous meta tags
audio.delete()

#get album picture data
cover ="http://cont-sv5-2.pandora.com/images/public/amz/5/2/9/7/095115137925_500W_488H.jpg"
fd = urllib.urlopen(cover)
image_file = io.BytesIO(fd.read())
ima = Image.open(image_file)
im = ima.tostring()

#processing
#I think it is here where it breaks
covr = []
if cover.endswith('png'):
    covr.append(MP4Cover(im,MP4Cover.FORMAT_PNG))
else:
    covr.append(MP4Cover(im,MP4Cover.FORMAT_JPEG))

#add cover
audio['covr'] = covr
#save everything
audio.save()
  • 我知道它会添加除图像之外的所有标签,因为我可以打开它 itunes正确,除了专辑封面以外的所有内容都是空白的
  • 当我ima.show()时,它会给我图像

因为这个我相信它可能会破坏这条线: covr.append(MP4Cover(im,MP4Cover.FORMAT_JPEG))

任何想法?是否有其他方法可以从网址获取图像?

1 个答案:

答案 0 :(得分:2)

这对我有用:

fd = urllib.urlopen(cover)
# Drop the entire PIL part
covr = MP4Cover(fd.read(), getattr(
            MP4Cover,
            'FORMAT_PNG' if cover.endswith('png') else 'FORMAT_JPEG'
        ))
fd.close() # always a good thing to do

audio['covr'] = [covr] # make sure it's a list
audio.save()