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

1

0

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?

Trixie answered 25/4, 2014 at 19:18 Comment(1)
Try skipping the io and PIL parts: audio['covr'] = MP4Cover(fd.read(), MP4Cover.FORMAT_JPEG), converting bytes to string might be the issue here.Ivoryivorywhite
I
2

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()
Ivoryivorywhite answered 25/4, 2014 at 20:2 Comment(1)
for python3 is urllib.request.urlopenWollastonite

© 2022 - 2024 — McMap. All rights reserved.