我对 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 上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
为什么我不能插入 Python 列表?Why I cannot make an insert to Python list?(为什么我不能插入 Python 列表?)
在 DataFrame 的开头(最左端)插入一列Insert a column at the beginning (leftmost end) of a DataFrame(在 DataFrame 的开头(最左端)插入一列)
Python psycopg2 没有插入到 postgresql 表中Python psycopg2 not inserting into postgresql table(Python psycopg2 没有插入到 postgresql 表中)
list extend() 索引,不仅将列表元素插入到末尾list extend() to index, inserting list elements not only to the end(list extend() 索引,不仅将列表元素插入到末尾)
如何使用 list.insert 将 Python 中的元素添加到列表How to add element in Python to the end of list using list.insert?(如何使用 list.insert 将 Python 中的元素添加到列表末尾?)
TypeError:“浮动"对象不可下标TypeError: #39;float#39; object is not subscriptable(TypeError:“浮动对象不可下标)