python-3.x - 将 PIL/Pillow 图像转换为数据 URL

标签 python-3.x image

在 Python3 中,是否可以将 PIL/Pillow Image 对象转换为 data:image/png URL,以便在粘贴到浏览器地址栏时, 图像出现了吗?

到目前为止我的尝试都失败了:

"data:image/png,{}".format(image_obj.tobytes())

或者,是否有任何其他好方法可以从 Python 脚本向远程用户发送图像?图像托管网站会很好,但通常很昂贵/没有 Python API/需要注册和登录。目前我打算使用像 Pastebin 这样的服务以文本形式存储图像并简单地将 URL 发送给用户.

最佳答案

实际上您使用了错误的前缀。你应该这样做:

img_data_url = 'data:image/jpeg;base64,' + base64_image_string

一些有用的东西:

import base64
import io
from PIL import Image


def pillow_image_to_base64_string(img):
    buffered = io.BytesIO()
    img.save(buffered, format="JPEG")
    return base64.b64encode(buffered.getvalue()).decode("utf-8")


def base64_string_to_pillow_image(base64_str):
    return Image.open(io.BytesIO(base64.decodebytes(bytes(base64_str, "utf-8"))))


# Example for Converting pillow image to base64 data URL to view in browser
my_img = Image.open('my-image.jpeg')
data_url = 'data:image/jpeg;base64,' + pillow_image_to_base64_string(my_img)
# You can put this data URL in the address bar of your browser to view the image

关于python-3.x - 将 PIL/Pillow 图像转换为数据 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60676893/

相关文章:

python - Python 中随机的字典数据类型

image - Golang Overlay 图像总是黑白的

ios - 似乎是 GPUImagePinchDistortionFilter 中的错误。谁能提供解决方案?

html - 为什么我的图像下面有空间?

HTML 图片调整大小和居中

android - Android的WebView可以自动调整大图的大小吗?

python - 将切片变为范围

python-3.x - 如何使用 `http.server` 实现一个简单的 Captive Portal?

python - 嵌套在另一个数据类中的数据类无法正确更新数据

python-3.x - 如何用新的 fs.HadoopFileSystem 替换旧的遗留 hdfs 连接器?