Home > Programming, Python > Python CGI Display Image

Python CGI Display Image

February 27, 2012 Leave a comment Go to comments

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: http://stackoverflow.com/questions/7389567/output-images-to-html-using-python

A tutorial of some basic examples of using python-cgi: http://www.tutorialspoint.com/python/python_cgi_programming.htm


Categories: Programming, Python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: