Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning image using stream instead of static_file in Bottle

I have a simple server app written in Python using Bottle framework. At one route I create an image and write it to a stream and I want to return it as a response. I know how to return an image file using static_file function but this is costly for me since I need to write the image to a file first. I want to serve the image directly using the stream object. How can I do this?

My current code is something like this (file version):

@route('/image')
def video_image():
    pi_camera.capture("image.jpg", format='jpeg')

    return static_file("image.jpg",
                       root=".",
                       mimetype='image/jpg')

Instead of this, I want to do something like this:

@route('/image')
def video_image():
    image_buffer = BytesIO()
    pi_camera.capture(image_buffer, format='jpeg') # This works without a problem

    # What to write here?
like image 624
Canol Gökel Avatar asked Feb 12 '23 03:02

Canol Gökel


1 Answers

Just return the bytes. (You should also set the 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
like image 65
ron rothman Avatar answered Feb 16 '23 04:02

ron rothman