python - 如何从 Python 中的 bytes 获取 image?

我有一个 image (jpeg)。我只需使用 open('img.jpg', 'rb') 从中获取 bytes。例如,我将 bytes 发送给我的朋友。那么使用 Python 的哪种方式可以得到相反的操作——从 bytes 到 image?如何解码?

  1. 如果他知道 format - 例如JPEG。
  2. 如果他不知道 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-imagehttps://stackoverflow.com/questions/14759637/python-pil-bytes-to-image吗?它们与您的情况非常相似。如果您将它们转换为 bytes,image 的 AFAIK 原始 format 也没有任何区别。所以链接的问题/答案应该没问题。但是,如果它们不起作用,请更新您的问题。

相似文章

pygame - 为什么我会收到 Recursion 语句?

我所做的只是将更多的精灵添加到名为ALL(forsprites)的列表和相应的函数中。我希望一切都会好起来,但具有讽刺意味的是,当运行整个代码时,我却没有收到一个关于递归错误的错误,它基本上是重复多次...

随机推荐

最新文章