通过StringIO打开的PIL图像在保存时返回NoneType错误

时间:2014-04-05 21:42:40

标签: python io python-imaging-library

我使用类似于此处的客户端/服务器接收图像流:http://picamera.readthedocs.org/en/release-1.3/recipes1.html#capturing-to-a-network-stream

这是服务器部分:

    server_socket = socket.socket()
    server_socket.bind(('0.0.0.0', 8000))
    server_socket.listen(0)

    connection = server_socket.accept()[0].makefile('rb')
    try:
            while True:
                    image_len = struct.unpack('<L', connection.read(4))[0]
                    if not image_len:
                            break
            #       image_stream = io.BytesIO()
                    image_stream = StringIO()
                    image_stream.write(connection.read(image_len))

                    image_stream.seek(0)
                    image = Image.open(image_stream)
                    print('image is %dx%d' % image.size)
                    print(type(image))
                    image.verify()
                    img_io = StringIO()
            #       img_io = io.BytesIO()
                    image.save('/tmp/test.jpg')
                    image.save(img_io, format='PNG', quality=70)
                    img_io.seek(0)
            #       print('image is verified')
                    return send_file(img_io, mimetype='image/png')
    finally:
            connection.close()
            server_socket.close()

连接成功,但返回以下内容:

image is 640x480
<type 'instance'>
File "/camserver.py", line 29, in start_server image.save('/tmp/test.jpg')
File "/lib/python2.7/site-packages/PIL/Image.py", line 1406, in save
self.load()
File "/lib/python2.7/site-packages/PIL/ImageFile.py", line 170, in load
read = self.fp.read
AttributeError: 'NoneType' object has no attribute 'read'

我尝试了BytesIO和StringIO的多种组合,看起来像是按预期返回了图像的size属性,但我无法将其保存到类文件对象或实际文件中。

编辑:奥米德拥有它。来自.verify上的文档:

&#34; ...此外,如果您需要在使用此方法后加载图像,则必须重新打开图像文件&#34;

0 个答案:

没有答案