在 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/