I currently working on generating an image, that needs to be encoded and decoded as base64 in different steps. However, I always get an error encoding error. I tried to save the image in between, change the encoding but it always comes down to the same error.
r2 = base64.b64decode(r.encode(“utf-8”),
validate=True).decode(“utf-8”) UnicodeDecodeError: ‘utf-8’ codec can’t
decode byte 0x89 in position 0: invalid start byte
Here is a minimal example:
<code>from PIL import Image
import base64
import io
if __name__ == "__main__":
# Create an image with a blue background
img = Image.new('RGB', (100, 100), color='blue')
# Save the image to a bytes buffer
buf = io.BytesIO()
img.save(buf, format='PNG')
buf.seek(0)
r = str(base64.b64encode(buf.read()).decode('utf-8'))
print(r)
# This operation throws an error and this cannot be changed
r2 = base64.b64decode(r.encode("utf-8"), validate=True).decode("utf-8")
print(r2)
</code>
<code>from PIL import Image
import base64
import io
if __name__ == "__main__":
# Create an image with a blue background
img = Image.new('RGB', (100, 100), color='blue')
# Save the image to a bytes buffer
buf = io.BytesIO()
img.save(buf, format='PNG')
buf.seek(0)
r = str(base64.b64encode(buf.read()).decode('utf-8'))
print(r)
# This operation throws an error and this cannot be changed
r2 = base64.b64decode(r.encode("utf-8"), validate=True).decode("utf-8")
print(r2)
</code>
from PIL import Image
import base64
import io
if __name__ == "__main__":
# Create an image with a blue background
img = Image.new('RGB', (100, 100), color='blue')
# Save the image to a bytes buffer
buf = io.BytesIO()
img.save(buf, format='PNG')
buf.seek(0)
r = str(base64.b64encode(buf.read()).decode('utf-8'))
print(r)
# This operation throws an error and this cannot be changed
r2 = base64.b64decode(r.encode("utf-8"), validate=True).decode("utf-8")
print(r2)