PIL.Image.save()到FTP服务器 [英] PIL.Image.save() to an FTP server

查看:623
本文介绍了PIL.Image.save()到FTP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  pilimg = PILImage.open(img_file_tmp)#img_file_tmp只包含图片阅读
pilimg.thumbnail((200,200),PILImage.ANTIALIAS)
pilimg.save(fn,'PNG')#fn是一个文件名
pre>

这适用于保存到由 fn 指向的本地文件。但是,我希望这样做是为了将文件保存在远程FTP服务器上。



实现此目的的最简单方法是什么?

解决方案

Python's ftplib 可以启动FTP传输,但PIL无法直接写入FTP服务器。



你可以做的是将结果写入文件,然后使用FTP库将其上传到FTP服务器。有关如何在 ftplib 手册中进行连接的完整示例,所以我只关注发送部分:

<$ (假设你已经创建了一个FTP
#的实例作为ftp,并已经登录)
f = open(fn,'r')
ftp.storbinary(STOR remote_filename.png,f)

如果您有足够的内存压缩的图像数据,您可以通过将PIL写入 StringIO ,然后将该对象传递给FTP库:

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

f.seek(0)#将StringIO的文件指针返回到文件的开头

#再假设你已经连接并登录了
ftp.storbinary(STOR remote_filename.png,f)


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?

解决方案

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)

If you have enough memory for the compressed image data, you can avoid the intermediate file by having PIL write to a StringIO, and then passing that object into the FTP library:

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)

这篇关于PIL.Image.save()到FTP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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