Stay Hungry,Stay Foolish!

image to/from base64

langchain_core.utils.image

https://api.python.langchain.com/en/latest/_modules/langchain_core/utils/image.html

import base64
import mimetypes


[docs]def encode_image(image_path: str) -> str:
    """Get base64 string from image URI.

    Args:
        image_path: The path to the image.

    Returns:
        The base64 string of the image.
    """
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")



[docs]def image_to_data_url(image_path: str) -> str:
    """Get data URL from image URI.

    Args:
        image_path: The path to the image.

    Returns:
        The data URL of the image.
    """
    encoding = encode_image(image_path)
    mime_type = mimetypes.guess_type(image_path)[0]
    return f"data:{mime_type};base64,{encoding}"

 

How do you base-64 encode a PNG image for use in a data-uri in a CSS file?

https://stackoverflow.com/questions/6375942/how-do-you-base-64-encode-a-png-image-for-use-in-a-data-uri-in-a-css-file

import base64

binary_fc       = open(filepath, 'rb').read()  # fc aka file_content
base64_utf8_str = base64.b64encode(binary_fc).decode('utf-8')

ext     = filepath.split('.')[-1]
dataurl = f'data:image/{ext};base64,{base64_utf8_str}'

 

How to embed .png into HTML email?

https://stackoverflow.com/questions/44832812/how-to-embed-png-into-html-email?noredirect=1&lq=1

 

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

 

Convert string in base64 to image and save on filesystem

https://stackoverflow.com/questions/2323128/convert-string-in-base64-to-image-and-save-on-filesystem?rq=3

# In Python 2.7
fh = open("imageToSave.png", "wb")
fh.write(img_data.decode('base64'))
fh.close()

# or, more concisely using with statement
with open("imageToSave.png", "wb") as fh:
    fh.write(img_data.decode('base64'))

 

posted @ 2024-11-29 21:34  lightsong  阅读(6)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel