如何在python中将图像(从request.FILES获取)转换为字节数组?

Moh*_*ria 1 python io file

假设我有一个图像文件类型的变量“profile_image”。我创建了如下变量:

profile_image = request.FILES.get('profile_image', False) 
Run Code Online (Sandbox Code Playgroud)

现在我需要将此图像变量转换为字节数组。如何在不将其保存到本地驱动器的情况下执行此操作?我发现文件打开/读取在这里不起作用。我试过如下:

with open(profile_image.name, "rb") as imageFile:
       file_stream = imageFile.read()
Run Code Online (Sandbox Code Playgroud)

请帮我。顺便说一句,通过转换为字节数组,我想将其保存到谷歌云。

谢谢你。

Moh*_*ria 5

谷歌搜索了很长时间后,我在这里找到了解决方案。

实际上“profile_image”是python中的“InMemoryUploadedFile”对象。我们可以像下面这样读取文件:

profile_image.file.read()
Run Code Online (Sandbox Code Playgroud)