Python Mutagen: add cover photo/album art by url?

╄→尐↘猪︶ㄣ 提交于 2019-12-25 07:09:31

问题


Using mutagen, I am able to add normal metatags such as title, artist, and genre however when I try to add an image via a url, it doesn't work.

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()
  • I know it adds all tags except the image because I can open it with itunes correctly, all except the album art is blank
  • when I do ima.show() it gives me the image

because of this I believe that it probably breaks around this line: covr.append(MP4Cover(im,MP4Cover.FORMAT_JPEG))

any ideas? Is there another way to get the image from a url?


回答1:


This works for me:

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()


来源:https://stackoverflow.com/questions/23301256/python-mutagen-add-cover-photo-album-art-by-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!