在 Bottle 中使用流而不是 static_file 返回图像
Returning image using stream instead of static_file in Bottle
我有一个使用 Bottle 框架用 Python 编写的简单服务器应用程序。在一条路线上,我创建了一个图像并将其写入流,我想 return 它作为响应。我知道如何使用 static_file 函数 return 图像文件,但这对我来说成本很高,因为我需要先将图像写入文件。我想直接使用流对象提供图像。我该怎么做?
我现在的代码是这样的(文件版本):
@route('/image')
def video_image():
pi_camera.capture("image.jpg", format='jpeg')
return static_file("image.jpg",
root=".",
mimetype='image/jpg')
而不是这个,我想做这样的事情:
@route('/image')
def video_image():
image_buffer = BytesIO()
pi_camera.capture(image_buffer, format='jpeg') # This works without a problem
# What to write here?
只是 return 个字节。 (您还应该设置 Content-Type header。)
@route('/image')
def video_image():
image_buffer = BytesIO()
pi_camera.capture(image_buffer, format='jpeg') # This works without a problem
image_buffer.seek(0) # this may not be needed
bytes = image_buffer.read()
response.set_header('Content-type', 'image/jpeg')
return bytes
我有一个使用 Bottle 框架用 Python 编写的简单服务器应用程序。在一条路线上,我创建了一个图像并将其写入流,我想 return 它作为响应。我知道如何使用 static_file 函数 return 图像文件,但这对我来说成本很高,因为我需要先将图像写入文件。我想直接使用流对象提供图像。我该怎么做?
我现在的代码是这样的(文件版本):
@route('/image')
def video_image():
pi_camera.capture("image.jpg", format='jpeg')
return static_file("image.jpg",
root=".",
mimetype='image/jpg')
而不是这个,我想做这样的事情:
@route('/image')
def video_image():
image_buffer = BytesIO()
pi_camera.capture(image_buffer, format='jpeg') # This works without a problem
# What to write here?
只是 return 个字节。 (您还应该设置 Content-Type header。)
@route('/image')
def video_image():
image_buffer = BytesIO()
pi_camera.capture(image_buffer, format='jpeg') # This works without a problem
image_buffer.seek(0) # this may not be needed
bytes = image_buffer.read()
response.set_header('Content-type', 'image/jpeg')
return bytes