如何在python中解码JPG / PNG?

时间:2017-02-04 05:37:03

标签: python image

这是JPG / PNG的代码(我不确切知道) Here's on google docs

我需要在Python中解码它以完成图像并使用Pillow或类似的东西显示它。你知道任何库或方法如何解码它?谢谢!

1 个答案:

答案 0 :(得分:1)

(对于Python 3)

如果图像存储为二进制文件,请直接打开它:

import PIL

# Create Image object
picture = PIL.Image.open('picture_code.dat')

#display image
picture.show()

# print whether JPEG, PNG, etc.
print(picture.format)

如果图片以十六进制形式存储在与您的Google文档链接类似的纯文本文件picture_code.dat中,则需要先将其转换为二进制数据:

import binascii
import PIL
import io

# Open plaintext file with hex
picture_hex = open('picture_code.dat').read()

# Convert hex to binary data
picture_bytes = binascii.unhexlify(picture_hex)

# Convert bytes to stream (file-like object in memory)
picture_stream = io.BytesIO(picture_bytes)

# Create Image object
picture = PIL.Image.open(picture_stream)

#display image
picture.show()

# print whether JPEG, PNG, etc.
print(picture.format)