valio174
Posts: 4
Joined: Sun Mar 18, 2018 7:24 pm
Location: Bulgaria
Contact: Website

Http server can't show image

Sun Mar 18, 2018 8:24 pm

Hello,
I have recently bought a Raspberry Pi Zero and an infrared camera. I want to make an http server which serves pictures that will be captured when a Pir sensor detects movement. I run a python script listening for movement, taking pictures and saving them to a folder. I want to make a dynamic http server using python. The pictures are in /home/pi/raspberryProject. In the same folder is the python script for the http server. I am using BaseHTTPServer module. This is the html part:

Code: Select all

        """Respond to a GET request."""
        s.send_response(200)
        s.send_header("Content-type", "text/html")
        s.end_headers()
        s.wfile.write("<html>")
        s.wfile.write("<body><img src=\"img.jpg\">")
        s.wfile.write("<body><img src=\"/img.jpg\">") #both don't work
        s.wfile.write("</body></html>")
When I run the server the image doesn't appear. How to use images from storage as img src attribute? I tried with apache. Modified the /var/www/html/index.html and put some pictures in that folder and it works, but it is static html and I want to use python.
Thanks for any help and comments

User avatar
KLL
Posts: 1453
Joined: Wed Jan 09, 2013 3:05 pm
Location: thailand
Contact: Website

Re: Http server can't show image

Mon Mar 19, 2018 4:48 am

using the index.html way
Image
with:
index.html

Code: Select all

<html><body>
show this content of index.html<br>
and now show a picture from same path<br>
<img src='img.jpg' alt='img.jpg' width='320' >

</body></html>
and
my_server.py i got from here

Code: Select all

#!/usr/bin/python

# from https://www.acmesystems.it/python_http

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep

PORT_NUMBER = 4000

#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):
	
	#Handler for the GET requests
	def do_GET(self):
		if self.path=="/":
			self.path="/index.html"

		try:
			#Check the file extension required and
			#set the right mime type

			sendReply = False
			if self.path.endswith(".html"):
				mimetype='text/html'
				sendReply = True
			if self.path.endswith(".jpg"):
				mimetype='image/jpg'
				sendReply = True
			if self.path.endswith(".gif"):
				mimetype='image/gif'
				sendReply = True
			if self.path.endswith(".js"):
				mimetype='application/javascript'
				sendReply = True
			if self.path.endswith(".css"):
				mimetype='text/css'
				sendReply = True

			if sendReply == True:
				#Open the static file requested and send it
				f = open(curdir + sep + self.path) 
				self.send_response(200)
				self.send_header('Content-type',mimetype)
				self.end_headers()
				self.wfile.write(f.read())
				f.close()
			return


		except IOError:
			self.send_error(404,'File Not Found: %s' % self.path)

try:
	#Create a web server and define the handler to manage the
	#incoming request
	server = HTTPServer(('', PORT_NUMBER), myHandler)
	print 'Started httpserver on port ' , PORT_NUMBER
	
	#Wait forever for incoming htto requests
	server.serve_forever()

except KeyboardInterrupt:
	print '^C received, shutting down the web server'
	server.socket.close()
( and the img.jpg file )
started with
python my_server.py
optional:
chmod +x my_server.py
./my_server.py

and called from local ( same RPI) browser with:
http://localhost:4000/
or
http://127.0.0.1:4000/
from LAN any PC browser with known RPI_IP
RPI_IP:4000

valio174
Posts: 4
Joined: Sun Mar 18, 2018 7:24 pm
Location: Bulgaria
Contact: Website

Re: Http server can't show image

Mon Mar 19, 2018 11:11 pm

Thank you for your help! How can I change the image source in the index.html dynamically? (I can use an script which opens the index.html file and changes the name of the source but then the server must be restarted) Basically my idea is to store 40 images in a folder and they will be displayed in the raspberry web server. A cycle counts to 40 and for each i in that cycle the camera captures a picture with name 'img{}.jpg'.format(i) . When i==40 the cycle starts once again from i=0. That way there will always be 40 pictures, but my problem is that they won't be arranged by time. (img1.jpg must be the newest picture and img40.jpg tha oldest). To do so, once there are 40 pictures I can set the name of every new picture 'img1.jpg' and rename the others with 'imgi+1.jpg' but I don't think that it is optimal. The other way is to get the images sorted by time of capture. I want to do something like this:

Code: Select all


###pseudo code
### starting the listing of the images

s.write('<h1>Gallery with images ordered by time of capture</h1>')

while images in dir:
    s.write('<img src=\"{}\"'.format(getLatestImg()))
       
s.write('<h3>After that there are 40 pictures and the oldest is last</h3>')
        

User avatar
KLL
Posts: 1453
Joined: Wed Jan 09, 2013 3:05 pm
Location: thailand
Contact: Website

Re: Http server can't show image

Tue Mar 20, 2018 12:48 am

sorry, i not say you must use a "static' index.html file,
combine your way of coding/feeding it
with the code i used to serve the files....
________________________________________________________________________
a other way could be again
make a static index.html with naming image files
img1.jpg
img2.jpg

use a python program ( pref the one what is saving images from camera )
and do following:
the original image files are like:
2018-03-20_07-24-15_snap.jpg ....
after saving you make a loop over all image files ( better read back full dirpath )
and make symlinks to them ( to the last 40 )( its a link so not takes disk space )
To create or update a symlink:

ln -sf /path/to/file /path/to/symlink
ln -sf 2018-03-20_07-24-15_snap.jpg img17.jpg
or with full path ( you must experiment about this... possibly so can serve pictures from any path... )
ln -sf /home/pi/Pictures/2018-03-20_07-24-15_snap.jpg /home/pi/my_server/img17.jpg
now that from index.html referred files exist ( are updated )
with this you can make/show any sequence of that pictures you want ( by time / size/ alphabet... )
without changing index.html ( or the server app )

p.s. here i made webserver / CMS with gallery by python flask

valio174
Posts: 4
Joined: Sun Mar 18, 2018 7:24 pm
Location: Bulgaria
Contact: Website

Re: Http server can't show image

Tue Mar 20, 2018 8:14 am

Thank you for your tips. For now I will make it with the symlinks and static html to get it working. Then I will try with python server.

User avatar
KLL
Posts: 1453
Joined: Wed Jan 09, 2013 3:05 pm
Location: thailand
Contact: Website

Re: Http server can't show image

Tue Mar 20, 2018 2:51 pm

ok, here some ideas for the details of a gallery version:
index.html made by file
gallery.html made by python


nano index.html

Code: Select all

<html><body>
show this content of index.html<br>
and now link to <a href="gallery.html">gallery</a><br>
</body></html>
nano gallery.css

Code: Select all

<style type="text/css">

.gallerycontainer{
position: relative;
/*Add a height attribute and set to largest image's height to prevent overlaying*/
}

.thumbnail img{
border: 1px solid white;
margin: 0 5px 5px 0;
}

.thumbnail:hover{
background-color: transparent;
}

.thumbnail:hover img{
border: 1px solid blue;

}

.thumbnail span{ /*CSS for enlarged image*/
position: absolute;
background-color: lightyellow;
padding: 5px;
left: -1000px;
border: 1px dashed gray;
visibility: hidden;
color: black;
text-decoration: none;
width: 615px;
}

.thumbnail span img{ /*CSS for enlarged image*/
border-width: 0;
padding: 2px;
width: 600px;
}

.thumbnail:hover span{ /*CSS for enlarged image*/
visibility: visible;
/* top: 180px; */ /*KLL fix top more nice but not work if picture list very long */
left: 30%;   /*KLL position where enlarged image should offset horizontally */
z-index: 50;

}

</style>
nano my_server.py

Code: Select all

#!/usr/bin/python

# from https://www.acmesystems.it/python_http

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep

PORT_NUMBER = 4000

#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):

        #Handler for the GET requests
        def do_GET(self):
                if self.path=="/":
                        self.path="/index.html"

                try:
                        #Check the file extension required and
                        #set the right mime type

                        sendReply = False
                        if self.path.endswith(".html"):
                                mimetype='text/html'
                                sendReply = True
                        if self.path.endswith(".jpg"):
                                mimetype='image/jpg'
                                sendReply = True
                        if self.path.endswith(".png"):
                                mimetype='image/png'
                                sendReply = True
                        if self.path.endswith(".gif"):
                                mimetype='image/gif'
                                sendReply = True
                        if self.path.endswith(".js"):
                                mimetype='application/javascript'
                                sendReply = True
                        if self.path.endswith(".css"):
                                mimetype='text/css'
                                sendReply = True

                        if self.path == "/gallery.html":
                                self.send_response(200)
                                self.send_header('Content-type',mimetype)
                                self.end_headers()
                                self.wfile.write("<html><body>")
                                self.wfile.write("<link rel=\"stylesheet\" href=\"gallery.css\" />")

                                for i in range(1, 41):
                                        myfile = "img"+str(i)+".jpg"
                                        myimage = "<a class=\"thumbnail\" href=\"#thumb\"><img src=\"" + myfile + "\" alt = \"" + myfile + "\" width = \"80\"></br><span><img src=\"" + myfile + "\" /></span></a>"
                                        self.wfile.write(myimage)

                                self.wfile.write("</body></html>")


                                sendReply = False


                        if sendReply == True:
                                #Open the static file requested and send it
                                f = open(curdir + sep + self.path)
                                self.send_response(200)
                                self.send_header('Content-type',mimetype)
                                self.end_headers()
                                self.wfile.write(f.read())
                                f.close()
                        return


                except IOError:
                        self.send_error(404,'File Not Found: %s' % self.path)

try:
        #Create a web server and define the handler to manage the
        #incoming request
        server = HTTPServer(('', PORT_NUMBER), myHandler)
        print 'Started httpserver on port ' , PORT_NUMBER

        #Wait forever for incoming htto requests
        server.serve_forever()

except KeyboardInterrupt:
        print '^C received, shutting down the web server'
        server.socket.close()

nano start

Code: Select all

#!/bin/bash
# filename: start
# start a python2 server application
MYPATH='/home/pi/projects/py2_httpserver'
MYAPP='my_server.py'

# better make a little delay timer
echo '10s'
env sleep 5
echo '5s'
env sleep 5
echo 'start app / stop with [ctrl][c]'

#to avoid problems if we call local files ... from application we better walk there
cd $MYPATH
python $MYAPP

# keep terminal open
echo 'press enter to close'
read
chmod +x start

nano start.desktop

Code: Select all

[Desktop Entry]
Type=Application
Name=python serverstart
Exec=/home/pi/projects/py2_httpserver/start
Icon=network
Comment=start python2 webserver
Terminal=true
X-KeepTerminal=false
Categories=Network;
cp start.desktop /home/pi/Desktop/start.desktop
Image
Last edited by KLL on Tue Mar 20, 2018 4:04 pm, edited 1 time in total.

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: Http server can't show image

Tue Mar 20, 2018 3:58 pm

Would be much easier to implement this with python-flask rather than the BaseHTTPServer module...
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

User avatar
KLL
Posts: 1453
Joined: Wed Jan 09, 2013 3:05 pm
Location: thailand
Contact: Website

Re: Http server can't show image

Tue Mar 20, 2018 5:03 pm

scotty101 wrote:
Tue Mar 20, 2018 3:58 pm
Would be much easier to implement this with python-flask rather than the BaseHTTPServer module...
?easy? i don't know, but more powerful? elegant?,

to give a idea how PYTHON FLASK works/looks:
just for example the gallery.html from my MAKER BLOG see here
( a reduced version, with GPIO operation only ( password protected ) is there also available )

gallery.html

Code: Select all

{% include 'header.html' %}
<link rel="stylesheet" href="{{ url_for('static', filename='assets/css/gallery.css') }}" />
				<!-- Main -->
					<div id="main">
						<div class="inner">
						{% block body %}
						<div class="gallerycontainer">
						{% for entry in gallerylist %}
							<a class="thumbnail" href="#thumb"><img src="{{ url_for('static', filename='images/'+entry.pic ) }}" width="100px" height="66px" border="0" /><span><img src="{{ url_for('static', filename='images/'+entry.pic ) }}" /><br />{{ entry.rem }}</span></a>
							<br />
						{% else %}
							<li><em>Unbelievable.  No entries here so far</em>
						{% endfor %}
						</div>
						{% endblock %}
						</div>
					</div>
{% include 'footer.html' %} 
where you mix handed python lists ( made from database driven config )
with HTML code and use
partial HTML files ( from HTML 5 template ) to make one.
Image
Last edited by KLL on Wed Mar 21, 2018 12:32 pm, edited 3 times in total.

valio174
Posts: 4
Joined: Sun Mar 18, 2018 7:24 pm
Location: Bulgaria
Contact: Website

Re: Http server can't show image

Wed Mar 21, 2018 9:24 am

Thank you KLL this is what I needed. I should also check the flask framework.

Return to “Beginners”