简体   繁体   English

Python PIL以二进制模式将图像保存到内存

[英]Python PIL Save Image to Memory in Binary Mode

I'm reading in an image file from URL and use PIL to add a watermark to it. 我正在从URL中读取图像文件,并使用PIL向其添加水印。 Then I need to upload the processed image to a FTP server. 然后,我需要将处理后的图像上传到FTP服务器。 But after successful uploading, I only see a corrupted image (a "?" in the blank). 但是上传成功后,我只会看到损坏的图像(空白处是“?”)。 The FTP server requires binary mode uploading. FTP服务器需要二进制模式上载。 But I think I'm already using binary mode. 但是我想我已经在使用二进制模式了。 I have the following code: 我有以下代码:

from PIL import Image
import ftplib
import urllib2
import StringIO

try:
    img_file = urllib2.urlopen(img_url)
except Exception, e:
    print 'Warn: image cannot be downloaded

# get the image as file in memory and make video
try:
    im = Image.open(img_file)
except Exception, e:
    print 'Warn: image not valid

# paste_im = Image.open("../asset/logo.png")
# if paste_im is None:
#     print 'Error: paste_im is None'
#     return
# im = watermark(im, paste_im, position=(20, 16), opaque=0.5)

id = 'myID'
pw = 'myPw'
output = StringIO.StringIO()
im.save(output, format='JPEG')
try:
    session = ftplib.FTP('FTP_server_url', id, pw)
    session.storbinary('STOR image.jpg', output)
except ftplib.all_errors as e:
        print '%s' % e 
output.close()
session.quit()
print 'upload succeeded'

I later commented out: 我后来注释掉:

# paste_im = Image.open("../asset/logo.png")
# if paste_im is None:
#     print 'Error: paste_im is None'
#     return
# im = watermark(im, paste_im, position=(20, 16), opaque=0.5)

In order not to introduce extra complexity here, but it still fails. 为了在这里不引入额外的复杂性,但是它仍然失败。 I wonder in which step I might be wrong. 我想知道在哪一步我可能错了。

The old code works perfect: 旧代码可以完美地工作:

img_file = urllib.urlopen(img_url)
try:
    session = ftplib.FTP('FTP_server_url', id, pw)
    session.storbinary('STOR image.jpg', img_file)
except ftplib.all_errors as e:
    print 'error'
img_file.close()
session.quit()

But now I need to pass it to PIL first to do some processing. 但是现在我需要先将其传递给PIL进行一些处理。 Thanks a lot. 非常感谢。

因此,正如Klaus指出的那样, im.save(output, format='JPEG'会将写指针设置为文件的末尾,因此下一次读取(此处为storbinary )将返回0个字节。因此,我们应添加output.seek(0)在读取文件对象之前将其倒带。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM