【问题标题】:How to save image in-memory and upload using PIL?如何将图像保存在内存中并使用 PIL 上传?
【发布时间】:2019-08-04 04:45:52
【问题描述】:

我对 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' object has no attribute read

【问题讨论】:

  • 如果您查看docs.python.org/2/library/… 的文档,函数storbinary 的第二个参数应该是“使用其read() 方法读取到EOF 的打开文件对象”。您不能改为传递字符串

标签: python image ftp python-imaging-library


【解决方案1】:

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

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

【讨论】:

  • 或者对两个 python 版本都使用six.BytesIO()
【解决方案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

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 2013-01-05
    • 2021-09-25
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多