简体   繁体   中英

How to decode JPG/PNG in python?

This is a code of a JPG/PNG(I don't know exactly) Here's on google docs

I need to decode it in Python to complete image and show it using Pillow or something like that. Do you know any libraries or ways how to decode it? Thanks!

(for Python 3)

If the image is stored as a binary file, open it directly:

import PIL

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

#display image
picture.show()

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

If the image is stored as hex in a plaintext file picture_code.dat similar to your Google Docs link, it needs to first be converted to binary data:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM