How to convert base64 to image using Python

Free Python Code - Aug 26 '23 - - Dev Community

Hi πŸ™‚πŸ–

In this post, I will share with you how to convert base64 to images using Python. In the previous post, I tallked about How to convert image to base64 using Python

step 1

Import modules


import base64
from PIL import Image
from io import BytesIO
Enter fullscreen mode Exit fullscreen mode

step 2

We need base64 bytes for testing. I will convert an image to base64 using this code.

import base64
from PIL import Image
from io import BytesIO

with open('alone.jpg', 'rb') as img:
    base64_bytes = base64.b64encode(img.read())

Enter fullscreen mode Exit fullscreen mode

Now that we have a base64 bytes for testing, we need to convert it to an image.

img = Image.open(BytesIO(base64.b64decode(base64_bytes)))
img.save('out.jpg')
Enter fullscreen mode Exit fullscreen mode

You can also convert a base64 string to an image by using this code.

import base64
from PIL import Image
from io import BytesIO

with open('alone.jpg', 'rb') as img:
    base64_bytes = base64.b64encode(img.read())


base64_str = base64_bytes.decode()

img = Image.open(
    BytesIO(
        base64.decodebytes(bytes(base64_str, 'utf-8'))
    )
)

img.save('out.jpg')
Enter fullscreen mode Exit fullscreen mode

Now we're done πŸ€—

Don't forget to like and follow πŸ™‚

Support me on PayPal πŸ€—
https://www.paypal.com/paypalme/amr396

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .