How to use the mutagen.flac.Picture function in mutagen

To help you get started, we’ve selected a few mutagen examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github quodlibet / mutagen / tests / test_flac.py View on Github external
def test_largest_valid(self):
        f = FLAC(self.filename)
        pic = Picture()
        pic.data = b"\x00" * (2 ** 24 - 1 - 32)
        self.assertEqual(len(pic.write()), 2 ** 24 - 1)
        f.add_picture(pic)
        f.save()
github beetbox / mediafile / mediafile.py View on Github external
def fetch(self, mutagen_file):
        images = []
        if 'metadata_block_picture' not in mutagen_file:
            # Try legacy COVERART tags.
            if 'coverart' in mutagen_file:
                for data in mutagen_file['coverart']:
                    images.append(Image(base64.b64decode(data)))
            return images
        for data in mutagen_file["metadata_block_picture"]:
            try:
                pic = mutagen.flac.Picture(base64.b64decode(data))
            except (TypeError, AttributeError):
                continue
            images.append(Image(data=pic.data, desc=pic.desc,
                                type=pic.type))
        return images
github flccrakers / dj-tango / mutagen / flac.py View on Github external
Attributes:
        cuesheet (`CueSheet`): if any or `None`
        seektable (`SeekTable`): if any or `None`
        pictures (List[`Picture`]): list of embedded pictures
        info (`StreamInfo`)
        tags (`mutagen._vorbis.VCommentDict`)
    """

    _mimes = ["audio/flac", "audio/x-flac", "application/x-flac"]

    info = None
    tags = None

    METADATA_BLOCKS = [StreamInfo, Padding, None, SeekTable, VCFLACDict,
                       CueSheet, Picture]
    """Known metadata block types, indexed by ID."""

    @staticmethod
    def score(filename, fileobj, header_data):
        return (header_data.startswith(b"fLaC") +
                endswith(filename.lower(), ".flac") * 3)

    def __read_metadata_block(self, fileobj):
        byte = ord(fileobj.read(1))
        size = to_int_be(fileobj.read(3))
        code = byte & 0x7F
        last_block = bool(byte & 0x80)

        try:
            block_type = self.METADATA_BLOCKS[code] or MetadataBlock
        except IndexError:
github ubuntupodcast / podpublish / podpublish / encoder.py View on Github external
def ogg_coverart(config):
    print("Adding " + config.coverart_mime +  " cover art to " + config.ogg_file)
    coverart = config.coverart
    imgdata = open(coverart,'rb').read()

    im = Image.open(coverart)
    w,h = im.size

    p = Picture()
    p.data = imgdata
    p.type = 3
    p.desc = 'Cover'
    p.mime = config.coverart_mime
    p.width = w
    p.height = h
    p.depth = 24
    dt=p.write()
    enc=base64.b64encode(dt).decode('ascii')

    audio = OggVorbis(config.ogg_file)
    audio['metadata_block_picture']=[enc]
    audio.save()
github gumob / music-dl / music_dl / core / metadata.py View on Github external
# if not image_mime_type == "image/jpeg" and not image_mime_type == "image/png":
            #     raise InvalidMimeTypeException("Invalid image format.", image_mime_type)
            #
            # picture = flac.Picture()
            # picture.type = 3
            # picture.desc = 'front cover'
            # picture.data = image_data
            #
            # return picture

        elif contains_at_least(audio_mime_type, ['audio/x-flac']):

            if not image_mime_type == "image/jpeg" and not image_mime_type == "image/png":
                raise InvalidMimeTypeException("Invalid image format.", image_mime_type)

            picture = flac.Picture()
            picture.type = 3
            picture.desc = 'front cover'
            picture.data = image_data

            return picture

        else:
            raise InvalidMimeTypeException("Invalid audio format.", audio_mime_type)
github desbma / sacad / sacad / recurse.py View on Github external
def embed_album_art(cover_filepath, audio_filepaths):
  """ Embed album art into audio files. """
  with open(cover_filepath, "rb") as f:
    cover_data = f.read()

  for filepath in audio_filepaths:
    mf = mutagen.File(filepath)
    if (isinstance(mf.tags, mutagen._vorbis.VComment) or
            isinstance(mf, mutagen.ogg.OggFileType)):
      picture = mutagen.flac.Picture()
      picture.data = cover_data
      picture.type = mutagen.id3.PictureType.COVER_FRONT
      picture.mime = "image/jpeg"
      encoded_data = base64.b64encode(picture.write())
      mf["metadata_block_picture"] = encoded_data.decode("ascii")
    elif (isinstance(mf.tags, mutagen.id3.ID3) or
          isinstance(mf, mutagen.id3.ID3FileType)):
      mf.tags.add(mutagen.id3.APIC(mime="image/jpeg",
                                   type=mutagen.id3.PictureType.COVER_FRONT,
                                   data=cover_data))
    elif (isinstance(mf.tags, mutagen.mp4.MP4Tags) or
          isinstance(mf, mutagen.mp4.MP4)):
      mf["covr"] = [mutagen.mp4.MP4Cover(cover_data,
                                         imageformat=mutagen.mp4.AtomDataType.JPEG)]
    mf.save()
github superdima05 / tidalgrabber / tidal.py View on Github external
if ".m4a" not in url:
			download(track.album.image, 'music/'+name+'.png')
	except Exception:
		flac = 0
	if os.path.exists("music/"+name+".flac"):
		flac = 1
	if not os.path.exists("music/"+name+".flac"):
		flac = 0
	if ".flac" not in url:
		flac = 0
	if ".flac" in url:
		flac = 1
	if flac == 1:
		audio = FLAC("music/"+name+".flac")
		albumart = "music/"+name+".png"
		image = Picture()
		image.type = 3
		mime = 'image/png'
		image.desc = 'front cover'
		with open(albumart, 'rb') as f:
			image.data = f.read()
		audio['artist'] = track.artist.name
		audio['title'] = track.name
		audio['album'] = track.album.name
		audio['date'] = releaseDate
		audio.add_picture(image)
		audio.save()
		os.remove("music/"+name+".png")
	elif flac == 0:
		print(name+" isn't in flac or can't be downloaded in this country.")
	else:
		print("Unknown error.")
github LoliLin / CloudMan / run.py View on Github external
audio['title'] = track['name']

                    artists = []
                    artists_str = ''
                    for artist in track['ar']:
                        artists.append(artist['name'])
                        artists_str = artists_str + '/' + artist['name']

                    artists_str = artists_str[1:]
                    artists.append(artists_str)

                    audio['artist'] = artists
                    audio['album'] = track['al']['name']

                    image = Picture()
                    image.type = 3
                    image.desc = 'front cover'
                    image.mime = 'image/jpeg'
                    image.width = 640
                    image.height = 640
                    image.data = open(cover_file_path, 'rb').read()

                    audio.save()
                    audio.clear_pictures()
                    audio.add_picture(image)
                    log.debug(audio.tags)
                    audio.save()
                except FLACNoHeaderError:
                    log.error('Not a validate FLAC file!')
                    playlist_tracks.append(track)
                    track_error[track['id']] = 1