使用PIL映像的python post请求

2024-06-25 06:14:30 发布

您现在位置:Python中文网/ 问答频道 /正文

<PIL.WebPImagePlugin.WebPImageFile image mode=RGB size=1600x1600 at 0x1F4E779BA00>这是文件类型 当我做post请求时,我得到这个错误TypeError: a bytes-like object is required, not 'WebPImageFile'。如何将其转换为类似字节的对象


Tags: imagesizebytespilobjectmode错误rgb
1条回答
网友
1楼 · 发布于 2024-06-25 06:14:30

通过将其保存为某种文件格式。你不能把抽象像素推到电线上:)

本例假设远程端可以接受PNG文件

import io

image = ...  # However you get your image
bio = io.BinaryIO()  # `BinaryIO` is essentially a file in memory
image.save(bio, format="PNG")  # Since there is no filename,
                               # you need to be explicit about the format
bio.seek(0)  # rewind the file we wrote into
requests.post(..., files={'file': bio})

要向API发送文件名,还需要将文件指定为元组

requests.post(..., files={'file': ('image.png', bio)})

相关问题 更多 >