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 @   lightsong  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
历史上的今天:
2023-11-29 dns and forward proxy
千山鸟飞绝,万径人踪灭
点击右上角即可分享
微信分享提示