0

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
ClementWalter
  • 4,814
  • 1
  • 32
  • 54
  • When you `image.save(buffered, format="JPEG")` the data in `buffered` is already different than your opened image. – r.ook Dec 03 '18 at 14:24
  • @Idlehands can you explain me please? – ClementWalter Dec 03 '18 at 14:42
  • If you tried to `img2 = Image.open(buffered)` after the `image.save` line immediately, you will already notice `img != img2`. I have a feeling that when it tries to save it's not necessarily being saved in the same manner as the original, hence the difference. – r.ook Dec 03 '18 at 14:45
  • Perhaps a related question: https://stackoverflow.com/questions/33642690/python-pil-save-image-different-size-original – r.ook Dec 03 '18 at 14:52
  • @Idlehands you were right, opening the image with Pil already altered the binary content, see my answer below – ClementWalter Dec 03 '18 at 17:41

1 Answers1

0

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
ClementWalter
  • 4,814
  • 1
  • 32
  • 54