如何使用 PIL 将图像保存在内存中并上传?

How to save image in-memory and upload using PIL?

我是 Python 的新手。目前我正在制作一个原型,它可以拍摄图像、创建缩略图并将其上传到 ftp 服务器。

到目前为止,我已准备好获取图像、转换和调整大小部分。

我 运行 遇到的问题是使用 PIL (pillow) 图片库转换的图片类型与使用 storebinary() 上传时可以使用的图片类型不同

我已经尝试过一些方法,例如使用 StringIO 或 BufferIO 将图像保存在内存中。但我总是遇到错误。有时确实上传了图片,但文件似乎是空的(0 字节)。

这是我正在使用的代码:

import os
import io
import StringIO
import rawpy
import imageio
import Image
import ftplib

# connection part is working
ftp = ftplib.FTP('bananas.com')
ftp.login(user="banana", passwd="bananas")
ftp.cwd("/public_html/upload")

def convert_raw():
    files = os.listdir("/home/pi/Desktop/photos")

    for file in files:
        if file.endswith(".NEF") or file.endswith(".CR2"):
            raw = rawpy.imread(file)
            rgb = raw.postprocess()
            im = Image.fromarray(rgb)
            size = 1000, 1000
            im.thumbnail(size)

            ftp.storbinary('STOR Obama.jpg', img)
            temp.close()
    ftp.quit()

convert_raw()

我尝试了什么:

temp = StringIO.StringIO
im.save(temp, format="png")
img = im.tostring()
temp.seek(0)
imgObj = temp.getvalue()

我遇到的错误在 ftp.storbinary('STOR Obama.jpg', img).

留言:

buf = fp.read(blocksize)
attributeError: 'str' object has no attribute read

不要将字符串传递给 storbinary。您应该将文件或文件对象(memory-mapped 文件)传递给它。另外,这一行应该是 temp = StringIO.StringIO()。所以:

temp = StringIO.StringIO() # this is a file object
im.save(temp, format="png") # save the content to temp
ftp.storbinary('STOR Obama.jpg', temp) # upload temp

对于 Python 3.x 使用 BytesIO 而不是 StringIO:

temp = BytesIO()
im.save(temp, format="png")
ftp.storbinary('STOR Obama.jpg', temp.getvalue())