如何在Python中从字节中获取图像?

Rus*_*rov 1 python format byte image

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

  1. 如果他知道格式(例如 JPEG),则采用这种方式。
  2. 如果他不知道格式的话。有什么办法吗?

Pyt*_*CSJ 8

使用 PIL 模块。更多信息参见此处的答案:将图像字节数据流解码为 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))
Run Code Online (Sandbox Code Playgroud)