1

Right now, I have the following code:

pilimg = PILImage.open(img_file_tmp) # img_file_tmp just contains the image to read
pilimg.thumbnail((200,200), PILImage.ANTIALIAS)
pilimg.save(fn, 'PNG') # fn is a filename

This works just fine for saving to a local file pointed to by fn. However, what I would want this to do instead is to save the file on a remote FTP server.

What is the easiest way to achieve this?

4

1 回答 1

3

Python's ftplib library can initiate an FTP transfer, but PIL cannot write directly to an FTP server.

What you can do is write the result to a file and then upload it to the FTP server using the FTP library. There are complete examples of how to connect in the ftplib manual so I'll focus just on the sending part:

# (assumes you already created an instance of FTP
#  as "ftp", and already logged in)
f = open(fn, 'r')
ftp.storbinary("STOR remote_filename.png", f)

如果您有足够的内存用于压缩图像数据,则可以通过将 PIL 写入 a StringIO,然后将该对象传递到 FTP 库来避免中间文件:

import StringIO
f = StringIO()
image.save(f, 'PNG')

f.seek(0) # return the StringIO's file pointer to the beginning of the file

# again this assumes you already connected and logged in
ftp.storbinary("STOR remote_filename.png", f)
于 2013-03-30T07:20:54.187 回答