Skip to content

Instantly share code, notes, and snippets.

@nioto
Created March 4, 2014 10:14
Show Gist options
  • Save nioto/9343730 to your computer and use it in GitHub Desktop.
Save nioto/9343730 to your computer and use it in GitHub Desktop.
Simple MJpeg streamer for Raspberri Pi Camera
#!/usr/bin/python
'''
A Simple mjpg stream http server for the Raspberry Pi Camera
inspired by https://gist.github.com/n3wtron/4624820
'''
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import io
import time
import picamera
camera=None
class CamHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.endswith('.mjpg'):
self.send_response(200)
self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary')
self.end_headers()
stream=io.BytesIO()
try:
start=time.time()
for foo in camera.capture_continuous(stream,'jpeg'):
self.wfile.write("--jpgboundary")
self.send_header('Content-type','image/jpeg')
self.send_header('Content-length',len(stream.getvalue()))
self.end_headers()
self.wfile.write(stream.getvalue())
stream.seek(0)
stream.truncate()
time.sleep(.5)
except KeyboardInterrupt:
pass
return
else:
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write("""<html><head></head><body>
<img src="/cam.mjpg"/>
</body></html>""")
return
def main():
global camera
camera = picamera.PiCamera()
#camera.resolution = (1280, 960)
camera.resolution = (640, 480)
global img
try:
server = HTTPServer(('',8080),CamHandler)
print "server started"
server.serve_forever()
except KeyboardInterrupt:
camera.close()
server.socket.close()
if __name__ == '__main__':
main()
@guardrex
Copy link

I've tested it, and it works fine for me. Thanks for posting this ... it saved me a a lot of time and effort.

@hydraslay
Copy link

Dose't work for me....

  1. Is it correct to use url "http://xxxxx:8080/cam.mjpg" to access the picture?
  2. One more thing I don't get it .
    You put the image to the stream 0.5 second 1 time , but you never finish the response output?

@tobq
Copy link

tobq commented Aug 8, 2016

this dosnt work

@chrisribal
Copy link

Works perfectly for me! Thank you!
Although there can only be one viewer at a time - is there any way, to make it accessible for more persons at a time?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment