python - 将二进制图像数据转换为图像并以 HTML 显示

标签 python image musicbrainz binary-image

我正在使用 Musicbrainsngs - Musicbrainz API 的 Python 库。请求一些专辑插图。

import musicbrainzngs as mb

release_group_ID = '5c14fd50-a2f1-3672-9537-b0dad91bea2f'
artwork = mb.get_release_group_image_front(release_group_ID)
print(artwork)

documentation说它将以字符串形式返回“二进制图像数据”。

我想问你的问题: 这是什么类型的数据-(Base 64 编码的 PNG?我怎么知道?)

但更重要的是 - 我要用它做什么?如何将其保存为图像,或使用 HTML 将其显示为图像?

图像数据是 1mm 字符-这是开头的一个简短示例:

b'x16\x00\xe0}\xc1\x17\xfb_U{R\xd43uL\xbf\xe33\xec3e(,\xa7p\x00\xa2+\x02   \x9c\x92\xb6\x0b\x00\x07\xf9x\xeaa\xd5\x99 i\xab$\xe2\x92\xa3Co\xb9`\xb9\x1cd\x911\x01[\x0c\xd0\x9c\xaa\x81\x08Q|\x13\xe4\xd9:c\xa47\xfe\xca*q\xf5\xd4O\xea\x0fi\x9c\xcc\xf8u\x88\x0b\x16\x11m?#F\x9d\x9a\xe8}I&\xfe\xb5]t\xcf\xf0\x1f\xeb\xce\x9d\xa4iy^\x8b\xf7;2cde\xac\xd0\xc9\x12\x7f<I$)\rI\x90\xe3j\xc2!D\xdbg\xfe&\xf2:"rl;)\x98\n\x80\x9e \x1fS\x8e\x87\xce\xaa\xe0\x8a\xc2\x9b\'

最佳答案

看起来 API 确实没有填充此信息。

备选方案 1

只需将二进制数据按原样写入文件(以二进制方式)。然后使用 ma​​gic(一个 libmagic 包装器)来确定 mime 类型。并相应地重命名。

#! /usr/bin/python
# -*- coding: utf-8 -*-

import musicbrainzngs as mb
import magic
import os

release_group_ID = '5c14fd50-a2f1-3672-9537-b0dad91bea2f'
artwork = mb.get_release_group_image_front(release_group_ID)

result_file = 'result_file'

with open(result_file, 'wb') as file_handler:
    file_handler.write(artwork)

mime = magic.Magic(mime=True)
mime_type = mime.from_file(result_file)

if mime_type == 'image/jpeg':
    os.rename(result_file, result_file + '.jpg')
elif mime_type == 'image/png':
    os.rename(result_file, result_file + '.png')
elif mime_type == 'image/gif':
    os.rename(result_file, result_file + '.gif')
elif mime_type == 'image/bmp':
    os.rename(result_file, result_file + '.bmp')
elif mime_type == 'image/tiff':
    os.rename(result_file, result_file + '.tiff')
else:
    print('Not an image? %s' % mime_type)

备选方案 2

同样,只需按原样获取二进制数据并将其写入文件(以二进制模式)。现在用PIL 打开它并以你真正想要的格式保存它(PIL 不关心输入图像的格式,它支持大约 80 种不同的格式)。然后删除原文件。

#! /usr/bin/python
# -*- coding: utf-8 -*-

import musicbrainzngs as mb
from PIL import Image
import os

release_group_ID = '5c14fd50-a2f1-3672-9537-b0dad91bea2f'
artwork = mb.get_release_group_image_front(release_group_ID)

result_file = 'result_file'

with open(result_file, 'wb') as file_handler:
    file_handler.write(artwork)

Image.open(result_file).save(result_file + '.png', 'PNG')

os.remove(result_file)

关于python - 将二进制图像数据转换为图像并以 HTML 显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48917250/

相关文章:

python - 在后台更改 Windows 10 应用程序音频混合(最好使用 Python)

Python popen 命令。等待命令完成

python - 定期通过电子邮件发送 python 脚本输出的好方法是什么?

c++ - Win32 工具栏和 24 位图像

javascript - 所有图像的src与jquery

c# - .Net Maui 图像 BaseSize 混淆

mysql - musicbrainz 无法按国家/地区统计艺术家

python - 按 Artist_id 过滤 browser_release_groups 的结果以获取唱片目录,python

python - 正则表达式将结尾处的(所有匹配项或无匹配项)修复为 1

java - 获取艺术家的唱片目录,就像 musicbrainz 上的概览页面一样