問(wèn)題描述
我對(duì) Python 還很陌生.目前我正在制作一個(gè)原型,它可以拍攝一張圖片,從中創(chuàng)建一個(gè)縮略圖并將其上傳到 ftp 服務(wù)器.
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.
到目前為止,我已經(jīng)準(zhǔn)備好獲取圖像、轉(zhuǎn)換和調(diào)整大小.
So far I got the get image, convert and resize part ready.
我遇到的問(wèn)題是使用 PIL(枕頭)圖像庫(kù)轉(zhuǎn)換圖像的類(lèi)型與使用 storebinary() 上傳時(shí)可以使用的類(lèi)型不同
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()
我已經(jīng)嘗試了一些方法,例如使用 StringIO 或 BufferIO 將圖像保存在內(nèi)存中.但是我一直在出錯(cuò).有時(shí)圖像確實(shí)已上傳,但文件似乎為空(0 字節(jié)).
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()
我得到的錯(cuò)誤在于 ftp.storbinary('STOR Obama.jpg', img)
.
消息:
buf = fp.read(blocksize)
attributeError: 'str' object has no attribute read
推薦答案
不要將字符串傳遞給 storbinary
.您應(yīng)該將文件或文件對(duì)象(內(nèi)存映射文件)傳遞給它.此外,這一行應(yīng)該是 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
這篇關(guān)于如何將圖像保存在內(nèi)存中并使用 PIL 上傳?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!