简体   繁体   中英

How to properly encode and decode base64 image to get exact same image with python?

I am missing something during the operation because the images are not the same (though it is visually not possible to see a difference).

MWE:

import base64
from io import BytesIO

from PIL import Image

image = Image.open('image.jpg')
buffered = BytesIO()
image.save(buffered, format="JPEG")
image_content = base64.urlsafe_b64encode(buffered.getvalue())

image_decoded = Image.open(BytesIO(base64.urlsafe_b64decode(image_content.decode())))

print(image == image_decoded)
# return False
print(np.array(image).sum() == np.array(image_decoded).sum())
# return False

I finally sorted that out thanks to @Idlehands comment. Image.open(...) already altered the binary content.

A working solution:

import base64

from PIL import Image

with open('image_name.jpg', 'rb') as image_file:
    image_byte = image_file.read()
    image_base64 = base64.urlsafe_b64encode(image_byte)

with open('test.jpg', 'wb') as image_file:
    image_file.write(base64.urlsafe_b64decode(image_base64))


image = Image.open('image_name.jpg')
image_decoded = Image.open('test.jpg')
image == image_decoded

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