我对python还不太熟悉。目前,我正在制作一个原型,获取一个图像,从中创建一个缩略图并上传到ftp服务器。
到目前为止,我已经准备好获取图像,转换和调整部分大小。
我遇到的问题是,使用pil(枕头)图像库转换图像的类型不同于使用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()

我得到的错误就在这条线上。
消息:
buf = fp.read(blocksize)
attributeError: 'str' object has no attribute read

最佳答案

不要向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

07-24 19:00
查看更多