如何将图像保存在内存中并使用 PIL 上传? [英] How to save image in-memory and upload using PIL?

查看:37
本文介绍了如何将图像保存在内存中并使用 PIL 上传?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Python 还很陌生.目前我正在制作一个原型,它可以拍摄一张图片,从中创建一个缩略图并将其上传到 ftp 服务器.

I'm fairly new to Python. Currently I'm making a prototype that takes an image, creates a thumbnail out of it and and uploads it to the ftp server.

到目前为止,我已经准备好获取图像、转换和调整大小.

So far I got the get image, convert and resize part ready.

我遇到的问题是使用 PIL(枕头)图像库转换图像的类型与使用 storebinary() 上传时可以使用的类型不同

The problem I run into is that using the PIL (pillow) Image library converts the image is a different type than that can be used when uploading using storebinary()

我已经尝试了一些方法,例如使用 StringIO 或 BufferIO 将图像保存在内存中.但是我一直在出错.有时图像确实已上传,但文件似乎为空(0 字节).

I already tried some approaches like using StringIO or BufferIO to save the image in-memory. But I'm getting errors all the time. Sometimes the image does get uploaded but the file appears to be empty (0 bytes).

这是我正在使用的代码:

Here is the code I'm working with:

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

推荐答案

不要将字符串传递给 storbinary.您应该将文件或文件对象(内存映射文件)传递给它.此外,这一行应该是 temp = StringIO.StringIO().所以:

Do not pass a string to storbinary. You should pass a file or file object (memory-mapped file) to it instead. Also, this line should be temp = StringIO.StringIO(). So:

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

这篇关于如何将图像保存在内存中并使用 PIL 上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆