Python Mutagen:如何通过URL添加封面照片/专辑封面?
我在使用mutagen的时候,可以添加一些常见的元标签,比如title
(标题)、artist
(艺术家)和genre
(类型),但是当我尝试通过网址添加一张图片时,它却不行。
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 个回答
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()