Sunday, July 6, 2008

Showing a webcam image in the desktop window using Python. Part 1: reading image from web

I will describe everything that is necessary to show a window with a webcam (or any other) image in it. I'm using similar app to display a stock price chart (downloaded from a website) which is regularly updated. I will divide the text into three parts because I think this will be easier to grasp than one large article. This part will deal with downloading web content, in the second one the content will be displayed and in the third, final, one I will cover the self-refreshing which was the most difficult to figure out.
Again, I believe there is more than one way to do it. What follows is how I solved it.
There is a nice built-in library in Python called urllib which we will use to download the image in question.
The code is simple:

import urllib

def getimagefromweb(url):
'''Downloads content from given url and saves it as image.'''
u = urllib.urlopen(url) # open url
content = # read the openned url
u.close() # url was closed

except IOError:
print('Unknown url error')

# saving what was downloaded
f = open('img.jpg','wb')
f.close() # file was closed

myurl = ''
print 'all OK'

The (only) function "getimagefromweb" receives a url with content to be downloaded and then reads from this adress in the same way that is used when reading/writing files. When dealing with web it is very advisable to use error-catching code like this one. It is common that the website will not respond in time and without error catching your application would crash.
As a final task the function saves image to harddisk so that it can be later re-read and shown on the desktop. This is a workaroud because I could not figure out a way how to display it directly.
The url leads to the webcam of the main square of the Zatec city where I was born and have grown up. It has quite interesting medieval centre so its nice to have it shown on desktop :-)

No comments: