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

15

我对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

您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Unni
2个回答

32

对于Python 3.x,请使用BytesIO替代StringIO

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

或者在两个Python版本中都使用six.BytesIO() - mtoloo

7

不要将字符串传递给 storbinary。您应该传递文件或文件对象(内存映射文件)给它。此外,这一行应该是 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接