Python PIL将图像保存在内存中并上传

Ara*_*ash 3 python ftp image python-imaging-library

我对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()
Run Code Online (Sandbox Code Playgroud)

我尝试了什么:

temp = StringIO.StringIO
im.save(temp, format="png")
img = im.tostring()
temp.seek(0)
imgObj = temp.getvalue()
Run Code Online (Sandbox Code Playgroud)

错误我得到的谎言"ftp.storbinary('STOR Obama.jpg',img)"

消息:buf = fp.read(blocksize)attributeError:'str'对象没有读取属性

Rob*_*rdi 13

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

temp = BytesIO()
im.save(temp, format="png")
ftp.storbinary('STOR Obama.jpg', temp.getvalue())
Run Code Online (Sandbox Code Playgroud)


J F*_*ird 6

不要将字符串传递给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
Run Code Online (Sandbox Code Playgroud)