在Python3中,是否可以将PIL/PillowImage对象转换为data:image/pngURL,以便在粘贴到浏览器地址栏中时出现图像?
到目前为止我的尝试都失败了:
"data:image/png,{}".format(image_obj.tobytes())
Run Code Online (Sandbox Code Playgroud)
或者,是否有其他好方法将图像从 Python 脚本发送到远程用户?图像托管网站会很好,但通常很昂贵/没有 Python API/需要注册和登录。目前我打算使用像 Pastebin 这样的服务以文本形式存储图像,然后简单地将 URL 发送给用户。
实际上您使用了错误的前缀。你应该做:
img_data_url = 'data:image/jpeg;base64,' + base64_image_string
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2342 次 |
| 最近记录: |