如何在内存中保存图像并使用PIL上传? [英] How to save image in-memory and upload using 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屋!