我有一个 image (jpeg)。我只需使用 open('img.jpg', 'rb') 从中获取 bytes。例如,我将 bytes 发送给我的朋友。那么使用 Python 的哪种方式可以得到相反的操作——从 bytes 到 image?如何解码?
- 如果他知道 format - 例如JPEG。
- 如果他不知道 format 的方式。有什么办法吗?
回答1
使用 PIL 模块。此处答案中的更多信息:https://stackoverflow.com/questions/62348356/decode-image-bytes-data-stream-to-jpeg
from PIL import Image
from io import BytesIO
with open('img.jpg', 'rb') as f:
data = f.read()
# Load image from BytesIO
im = Image.open(BytesIO(data))
# Display image
im.show()
# Save the image to 'result.FORMAT', using the image format
im.save('result.{im_format}'.format(im_format=im.format))
回答2
如果您不想使用外部库,可以使用 byte 签名(即文件的前几个 bytes)来确定 image 压缩类型。
以下是一些常见的image formats。
img_types = {
b'\xFF\xD8\xFF\xDB': 'jpg',
b'\xFF\xD8\xFF\xE0': 'jpg',
b'\xFF\xD8\xFF\xEE': 'jpg',
b'\xFF\xD8\xFF\xE1': 'jpg',
b'\x47\x49\x46\x38\x37\x61': 'gif',
b'\x47\x49\x46\x38\x39\x61': 'gif',
b'\x42\x4D': 'bmp',
b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A': 'png'
}
with open('path/to/image', 'rb') as fp:
img_bytes = fp.read()
for k, v in img_types.items():
if img_bytes.startswith(k):
img_type = v
break
else:
img_type = None
回答3
你检查过https://stackoverflow.com/questions/18491416/pil-convert-bytearray-to-image和https://stackoverflow.com/questions/14759637/python-pil-bytes-to-image吗?它们与您的情况非常相似。如果您将它们转换为 bytes,image 的 AFAIK 原始 format 也没有任何区别。所以链接的问题/答案应该没问题。但是,如果它们不起作用,请更新您的问题。