【问题标题】:How to decode JPG/PNG in python?如何在 python 中解码 JPG/PNG?
【发布时间】:2017-02-04 05:37:02
【问题描述】:

这是一个 JPG/PNG 的代码(我不太清楚) Here's on google docs

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

【问题讨论】:

  • 请添加更多信息以及您已经尝试过的内容。
  • 这是一张 JPEG 图片。 (通过排除——它不是PNG图像,从它的标题可以看出。)

标签: python image


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-19
    • 2014-05-31
    • 2018-06-15
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 2020-01-28
    相关资源
    最近更新 更多