Posts Tagged ‘CGI’

Python CGI Display Image

February 27, 2012 Leave a comment

I was trying to write a simple html using python-cgi. It’s really a powerful tool ~ However, I had some problems of displaying the image with text. Here’s what I found:

1. You should only define one type of your html file. It should be either , or .  You can’t combine them! Basically, you would like to choose text type, but use the <img> tag to include your image.

2. Using <img> tag, the src field should be the link to the image.  Your images in web page is actually a second request to the server, so it should be a reference to the image — in other words, it should be “the url to your image”.

3. So, a question is, for example for my case, my web page is actually “self-usage” ( though sounds stupid) which I want to use it to display images in my local folder as well (not only images from another web url) — how can I do this? Here’s two different ways I found.

(a) put your image (you can also try other media files) into /cgi-bin/. For me I create a subfolder /cgi-bin/images. It seems that the server can found items under cgi-bin — I mean, each item under your cgi-bin actually has a url.  such as http://localhost:8000/cgi-bin/image/001.jpg . This will provide you a valid url for your image that you want to include.

(b) Since we have define our web as ‘text’. So to display an image read from local folder, you need to format the image somehow. Here’s what may work for you:

data_uri = open(r'D:/TEMP/yourimg.jpg', 'rb').read().encode('base64').replace('\n', '')
img_tag = '<img src="data:image/jpeg;base64,{0}" alt="" />'.format(data_uri)


You can get more information from here:

A tutorial of some basic examples of using python-cgi:

Categories: Programming, Python Tags: ,