Python 将字节文字转换为图像

Python Convert Bytes Literal To Image

在 Python3 我正在开发一个音乐播放应用程序。我正在使用一个名为 TinyTag 的库从音乐文件中获取元数据,例如标题和艺术家。它还支持获取专辑封面。当艺术品被检索到时,它会将其加载为我认为称为字节文字的内容(我不熟悉它)。我想知道如何将这些数据变成图像。这是代码:

from tinytag import TinyTag
tag = TinyTag.get("/path/to/file.mp3", image=True)
image_data = tag.get_image()
print(image_data)

图像数据是一个以字母 "b" 开头的巨大刺痛。它看起来像这样:

b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01...'

但要长得多。如何将其转换为专辑封面图像。需要哪些库以及如何实现?

您看到的字符串是图像文件的内容。您可以直接将字符串保存到文件中:

$ file /tmp/file.mp3
/tmp/file.mp3: Audio file with ID3 version 2.3.0, contains: MPEG ADTS, layer III, v1, 128 kbps, 44.1 kHz, JntStereo
$ ipython
Python 2.7.12 (default, Aug  9 2016, 15:48:18) 
Type "copyright", "credits" or "license" for more information.

IPython 3.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from tinytag import TinyTag

In [2]: tag = TinyTag.get("/tmp/file.mp3", image=True)

In [3]: image_data = tag.get_image()

In [4]: type(image_data)
Out[4]: str

In [5]: image_data[:20]
Out[5]: '\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00'

In [6]: with open("/tmp/album_art.jpg", "w") as f:
   ...:     f.write(image_data)
   ...:   

In [7]: exit()
$ file /tmp/album_art.jpg
/tmp/album_art.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, Exif Standard: [TIFF image data, big-endian, direntries=7, orientation=upper-left, xresolution=98, yresolution=106, resolutionunit=2, software=Adobe Photoshop CS2 Windows, datetime=2008:04:02 00:23:04], baseline, precision 8, 320x300, frames 3

如果您使用 python3,则必须在模式中明确指定 'wb',因为您得到的是字节流:

$ python3
Python 3.5.1 (default, Aug  9 2016, 15:35:51) 
[GCC 6.1.1 20160621 (Red Hat 6.1.1-3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from tinytag import TinyTag
>>> tag = TinyTag.get("/tmp/file.mp3", image=True)
>>> image_data = tag.get_image()
>>> type(image_data)
<class 'bytes'>
>>> image_data[:20]
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00'
>>> with open("/tmp/album_art.jpg", "wb") as f:
...     f.write(image_data)
... 
64790
>>> exit()
$ file /tmp/album_art.jpg
/tmp/album_art.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, Exif Standard: [TIFF image data, big-endian, direntries=7, orientation=upper-left, xresolution=98, yresolution=106, resolutionunit=2, software=Adobe Photoshop CS2 Windows, datetime=2008:04:02 00:23:04], baseline, precision 8, 320x300, frames 3