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

时间:2015-11-25 12:19:54

标签: python image ftp pillow

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

这个错误让我得到了谎言" ftp.storbinary(' STOR Obama.jpg',img)"

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

2 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:2)

不要将字符串传递给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
相关问题