SoFunction
Updated on 2024-11-21

Python image and base64 conversion details

Python Image Conversion

Work a lot of times using images and base64 conversion of each other, the following conversion code

quote

import base64
from PIL import Image
from io import BytesIO

base64 to image

method, input base64 string, and path to the image.

Store the image in the image path after conversion.

def base64_to_images(base64_str,image_path):
    # Decode base64 strings into bytes
    image_data = base64.b64decode(base64_str)
    # Convert byte data to image
    image = (BytesIO(image_data))
    # Save images locally
    (image_path)

Image to base64

Methods Store to txt as production base64 is too long.

Input: image path

txt path: convert to base64 to store in txt file

def image_to_base64(image_path,txt_path):
    # Open an image file
    with open(image_path, 'rb') as f:
        # Read the contents of an image file
        image_data = ()
        # Encoding image data as base64 strings
        base64_str = base64.b64encode(image_data)
    with open(txt_path,'wb') as txt_file:
        txt_file.write(base64_str)

call (programming)

if __name__ == "__main__":
    base64_str = "your base64 str"
    image_path = "E:\\temp\\"
    # base64_to_images(base64_str=base64_str,image_path=image_path)
    print('image saved')

    txt_path = "E:\\temp\\"
    image_to_base64(image_path,txt_path=txt_path)
    print('base64 saved')

to this article on the Python image and base64 conversion details of the article is introduced to this, more related Python image conversion content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!