473,714 Members | 2,412 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

CGI Proplem displaying image

Hi,
Maybe someone of you can help me.

I'm trying to display an image in memory(open file) with an cgi script
- but it want work proberly:

I'm running an Cgi webserver (CgiServerGui.p y).

both files are in the /cgi/ folder

############### ##
#my CGISRIPT: test.py

#! /usr/bin/env python

print ("Content-type: image/jpeg");
print # End of headers!

filename="cgi-bin//dog.jpg"
infile = open(filename, 'rb')
doginmemory=inf ile.read()
print doginmemory

############### ###

############### ##
#my html page with the image tag

<html>
<head>
</head>
<body>
<img type="image" src="/cgi-bin/test.py" height="25" width="111">
</body>
</html>

############### #
I can't figure out whats the problem.

funny: if I use a form with an method='post' I can get the picture
show up in a whole webpage ( method='get' will not work)

###########
<html>
<head>
</head>
<body>
<form name="test" method="post" action="/cgi-bin/test.py">
<input type="submit" value="go">
</body>
</html>
############
Any suggestion: (by the way: in the end the whole pictures should be
stored in an sqlite database and also retrieved from it to be
displayed within an html page.
Thanks Matthias
Jul 18 '05 #1
9 9579
Hello,

The HTTP header needs two newlines: one is provided by the "print"
statement but the other one shall be given by the string. Without the
second newline, the server returns an error 500 "Internal Error".

Karl

matthiasjanes wrote:
Hi,
Maybe someone of you can help me.

I'm trying to display an image in memory(open file) with an cgi script
- but it want work proberly:

I'm running an Cgi webserver (CgiServerGui.p y).

both files are in the /cgi/ folder

############### ##
#my CGISRIPT: test.py

#! /usr/bin/env python

print ("Content-type: image/jpeg");
print # End of headers!

filename="cgi-bin//dog.jpg"
infile = open(filename, 'rb')
doginmemory=inf ile.read()
print doginmemory

############### ###

############### ##
#my html page with the image tag

<html>
<head>
</head>
<body>
<img type="image" src="/cgi-bin/test.py" height="25" width="111">
</body>
</html>

############### #
I can't figure out whats the problem.

funny: if I use a form with an method='post' I can get the picture
show up in a whole webpage ( method='get' will not work)

###########
<html>
<head>
</head>
<body>
<form name="test" method="post" action="/cgi-bin/test.py">
<input type="submit" value="go">
</body>
</html>
############
Any suggestion: (by the way: in the end the whole pictures should be
stored in an sqlite database and also retrieved from it to be
displayed within an html page.
Thanks Matthias

Jul 18 '05 #2
ma***********@g mx.net (matthiasjanes) wrote in message news:<d5******* *************** ***@posting.goo gle.com>...
Hi,
Maybe someone of you can help me.

I'm trying to display an image in memory(open file) with an cgi script
- but it want work proberly:

I'm running an Cgi webserver (CgiServerGui.p y).

both files are in the /cgi/ folder

############### ##
#my CGISRIPT: test.py

#! /usr/bin/env python

print ("Content-type: image/jpeg");
print # End of headers!

filename="cgi-bin//dog.jpg"
infile = open(filename, 'rb')
doginmemory=inf ile.read()
print doginmemory

############### ###


Use sys.stdout for output in CGI scripts.
Escpecially with binary files.
Try this and see if the problem goes away

############### ##
#my CGISRIPT: test.py

#! /usr/bin/env python

import sys
sys.stdout("Con tent-type: image/jpeg\n\n")

filename="cgi-bin/dog.jpg"
img = open(filename, 'rb').read()
sys.stdout.writ e(img)

############### ###

Remember Google is your friend
http://starship.python.net/crew/davem/cgifaq/faqw.cgi

waldek
Jul 18 '05 #3
>
Use sys.stdout for output in CGI scripts.
Escpecially with binary files.
Try this and see if the problem goes away

############### ##
#my CGISRIPT: test.py

#! /usr/bin/env python

import sys
sys.stdout("Con tent-type: image/jpeg\n\n")

filename="cgi-bin/dog.jpg"
img = open(filename, 'rb').read()
sys.stdout.writ e(img)

############### ###

Remember Google is your friend
http://starship.python.net/crew/davem/cgifaq/faqw.cgi

waldek

Thanks to both of you,

Maybe my question was not clear enough: It is for me not a problem to
print the Image to screen. (As I said in the beginning) if I use a
form with methodes=post

example:

____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE
IMAGE_______

############### ##
#my CGISRIPT: test.py

#! /usr/bin/env python

print ("Content-type: image/jpeg");
print # End of headers!

filename="cgi-bin//dog.jpg"
infile = open(filename, 'rb')
doginmemory=inf ile.read()
print doginmemory

############### ###

############### ##
#my html page with the image tag

<html>
<head>
</head>
<body>
<form name="test" method="post" action="/cgi-bin/test.py"
target="_blank" >
<input type="submit" name="GO"> </form>
</body>
</html>
############### #
____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE
IMAGE_______

BUT What I want is that I display the image on an HTML page with text
together.
tables and .......

something like that

############### ##
#my html page with the image tag

<html>
<head>
</head>
<body>

Some Text
<img type="image" src="/cgi-bin/test.py" height="25" width="111">

some Text
</body>
</html>

############### #
A working example code - even very small one would be appreciated

Matthias Janes
Jul 18 '05 #4
ma***********@g mx.net (matthiasjanes) wrote in message news:<d5******* *************** ****@posting.go ogle.com>...

Use sys.stdout for output in CGI scripts.
Escpecially with binary files.
Try this and see if the problem goes away

############### ##
#my CGISRIPT: test.py

#! /usr/bin/env python

import sys
sys.stdout("Con tent-type: image/jpeg\n\n")

filename="cgi-bin/dog.jpg"
img = open(filename, 'rb').read()
sys.stdout.writ e(img)

############### ###

Remember Google is your friend
http://starship.python.net/crew/davem/cgifaq/faqw.cgi

waldek


Maybe my question was not clear enough: It is for me not a problem to
print the Image to screen. (As I said in the beginning) if I use a
form with method='post'

example:

____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE IMAGE_______

############### ##
#my CGISRIPT: test.py

#! /usr/bin/env python

print ("Content-type: image/jpeg");
print # End of headers!

filename="cgi-bin//dog.jpg"
infile = open(filename, 'rb')
doginmemory=inf ile.read()
print doginmemory

############### ###

############### ##
#my html page with the image tag

<html>
<head>
</head>
<body>
<form name="test" method="post" action="/cgi-bin/test.py" target="_blank" >
<input type="submit" name="GO"> </form>
</body>
</html>
############### #
____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE IMAGE_______

BUT What I want is that I display the image on an HTML page with text
together.
tables and .......

something like that

############### ##
#my html page with the image tag

<html>
<head>
</head>
<body>

Some Text
<img type="image" src="/cgi-bin/test.py" height="25" width="111">

some Text
</body>
</html>

############### #
A working example code - even very small one would be appreciated

Matthias Janes
Jul 18 '05 #5
ma***********@g mx.net (matthiasjanes) wrote in
news:d5******** *************** ***@posting.goo gle.com:
Some Text
<img type="image" src="/cgi-bin/test.py" height="25" width="111">


You are trying to mix HTML and the output of a Python script. That
won't work.
You'll have to use SSI (server side includes) to do this. With SSI you
could run a script from within a HTML page and print the output of the
script in that page.
Another solution: use a CGI-script and let that script generate the
whole HTML page.
Perhaps this would help to get you starting:
http://www.python.org/topics/web/

Matthias
Jul 18 '05 #6
"matthiasja nes" <ma***********@ gmx.net> wrote in message news:d5******** *************** ***@posting.goo gle.com...
ma***********@g mx.net (matthiasjanes) wrote in message
news:<d5******* *************** ****@posting.go ogle.com>...

BUT What I want is that I display the image on an HTML page with text
together.

You should have a script (if you don't want to have two different scripts),
which would return an image or a page depending on its parameters,
something like http://your.site.net/cgi-bin/witty_page.py?action=page to return
"""
....... Content-type: plain/text\n\n
.......<img src="witty_page .py?action=imag e">
.......
"""
and http://your.site.net/cgi-bin/witty_page.py?action=image to return a picture.

As an example, please have my counter script. It can return either a picture,
or a page: a 1x1 pix. picture when counting pages (...?site=999&a ctn=incr)
or an html page with the visitors list (...?site=999&a ctn=list).

Regards, Georgy

#!C:\Apps\Pytho n\python.exe

import sys, os

def read_counter( file_name ):
counter = "0"
if os.access( file_name, os.R_OK|os.W_OK ):
f = open( file_name, "rt" )
if f:
counter = f.read().strip( )
if counter == '': counter = "0"
f.close()
return counter

def write_counter( file_name, counter ):
f = open( file_name, "wt" )
if f:
f.write( counter )
f.close()

file_cnt = "counter/c_nn_%04d.dat" # i.e. in cgi-bin/counter/
file_ips = "counter/c_ip_%04d.dat"
file_dsc = "counter/c_descr.dat"

def show_list( site, name ):
file_cnt_name = file_cnt % site
file_ips_name = file_ips % site

counter = read_counter( file_cnt_name )

f = open( file_ips_name, "rt" )
if not f:
raise ValueError

lines = f.readlines()
f.close()

style = "<style>td { padding: 1px 6px 1px 6px; text-align: left; }</style>"
title = "<title>Vis its to %s</title>" % name

sys.stdout.writ e( "Content-type: text/html\n\n" ) # yield html

sys.stdout.writ e( "<html><head>%s %s</head>" % (style,title) )
sys.stdout.writ e( "<body>%s visits to <b>%s</b>"
"<p><table border=1 cellspacing=0>\ n" % (counter,name) )
sys.stdout.writ e( "<tr bgcolor='#C0FFF F'><td>%s</td><td>%s</td><td>%s</td></tr>\n"
% ('Date','Time', 'IP') )
try:
gray = False
for ln in lines:
ln = ln.strip()
if not ln:
continue
dt,tm,ip = ln.split()
if ip == '217.77.77.77': ip = 'my friend 1'
elif ip == '218.88.88.88': ip = 'my friend 2'
if gray: bg = "#E0E0E0"
else: bg = "#FFFFFF"
gray = not gray
sys.stdout.writ e( "<tr bgcolor='%s'><t d>%s</td><td>%s</td><td>%s</td></tr>\n"
% ( bg,dt,tm,ip ) )
except Exception,e:
sys.stdout.writ e( "<font color=red>%s</font>" % e )

sys.stdout.writ e( "</body></html>" )
sys.stdout.clos e()

def do_count( site ): # returns image

file_cnt_name = file_cnt % site
file_ips_name = file_ips % site

counter = read_counter( file_cnt_name )

counter = str(int(counter )+1)
write_counter( file_cnt_name, counter )

import datetime
dt = str(datetime.da tetime.now())[:-7]

ip = os.environ.get( "REMOTE_ADDR",' ?')

f = open( file_ips_name, "at" )
if f:
f.write( "%s %s\n" % (dt,ip) )
f.close()

return_image()

def return_image():
# 1x1 black pixel
data = ('GIF89a\x01\x0 0\x01\x00\x80\x 00\x00\x00\x00\ x00'
'\xFF\xFF\xFF\x 21\xF9\x04\x00\ x00\x00\x00\x00 '
'\x2C\x00\x00\x 00\x00\x01\x00\ x01\x00\x00\x02 \x03\x44\x01\x0 0\x3B')

sys.stdout.writ e( "Content-type: image/gif\n\n" )
sys.stdout.writ e( data )
sys.stdout.clos e()

def read_descriptio ns( filename ):
dict = {}
for line in file( filename ):
if not line or line[0]=='#': # ignore empty and comment lines
continue
fields = line.split()
if len(fields) < 2:
continue
num, title = fields[:2]
dict[int(num)] = title
return dict

sites = read_descriptio ns( file_dsc )

# now we accept:
# site=sitenumber (all digits)
# actn=list|incr

# How to insert a counter into your page:
# <img src="http://my.site.org/cgi-bin/counter.py?site =99&actn=incr"
# border=0 width=1 height=1 alt=''>

def processing():
try:
if os.environ.has_ key('QUERY_STRI NG'):
query = os.environ['QUERY_STRING']
import parsequery
query = parsequery.pars equery( query ) # get dictionary
if 'site' in query and 'actn' in query:
site = query['site']
actn = query['actn']
site = int(site)
if site in sites:
if actn == 'list':
show_list( site, sites[site] )
return
if actn == 'incr':
do_count( site )
return
except:
pass
# all bad cases -- just return a picture
return_image()

processing() # used to allow return from the middle

# EOF
Jul 18 '05 #7
> >
BUT What I want is that I display the image on an HTML page with text
together.

You should have a script (if you don't want to have two different scripts),
which would return an image or a page depending on its parameters,
something like http://your.site.net/cgi-bin/witty_page.py?action=page to return
"""
...... Content-type: plain/text\n\n
......<img src="witty_page .py?action=imag e">
......
"""
and http://your.site.net/cgi-bin/witty_page.py?action=image to return a picture.


sys.stdout.writ e( "Content-type: text/html\n\n" ) # yield html

sys.stdout.writ e( "<html><head>%s %s</head>" % (style,title) )
sys.stdout.writ e( "<body>%s visits to <b>%s</b>"
"<p><table border=1 cellspacing=0>\ n" % (counter,name) )
sys.stdout.writ e( "<tr bgcolor='#C0FFF F'><td>%s</td><td>%s</td><td>%s</td></tr>\n"
% ('Date','Time', 'IP') )


Thanks:

does anyone knows if the CGIHTTPServer.p y module can handle this kind of requests.

Do I have to use the 'sys.stdout.wri te( something )'

or is it also good enough to use 'print (something)'

regards

Matthias Janes
Jul 18 '05 #8

"matthiasja nes" <ma***********@ gmx.net> wrote in message news:d5******** *************** ***@posting.goo gle.com...

| Do I have to use the 'sys.stdout.wri te( something )'
|
| or is it also good enough to use 'print (something)'

Yes, "print something" will be quite safe here, although 'print' adds a newline mark
or a blank (if you end 'print' with a comma) to the output and sometimes it can show
on the generated pages. But if you used 'print' for making binary files e.g. images,
that could ruin the output, so it's usually easier to use sys.stdout.writ e and not to
think about this problem. Please note also, that on Windows, both of the ways can
translate '\n' into '\r\n' so it may be necessary to switch stdout to binary mode, with
this code, for example:
try:
import msvcrt,os
msvcrt.setmode( 1, os.O_BINARY ) # 1 = stdout; use 0 for stdin
except ImportError:
pass

Georgy
Jul 18 '05 #9
"Georgy" <no*****@availa ble.net> wrote in message news:<Ny******* *************@t wister.southeas t.rr.com>...
"matthiasja nes" <ma***********@ gmx.net> wrote in message news:d5******** *************** ***@posting.goo gle.com...

| Do I have to use the 'sys.stdout.wri te( something )'
|
| or is it also good enough to use 'print (something)'

Yes, "print something" will be quite safe here, although 'print' adds a newline mark
or a blank (if you end 'print' with a comma) to the output and sometimes it can show
on the generated pages. But if you used 'print' for making binary files e.g. images,
that could ruin the output, so it's usually easier to use sys.stdout.writ e and not to
think about this problem. Please note also, that on Windows, both of the ways can
translate '\n' into '\r\n' so it may be necessary to switch stdout to binary mode, with
this code, for example:
try:
import msvcrt,os
msvcrt.setmode( 1, os.O_BINARY ) # 1 = stdout; use 0 for stdin
except ImportError:
pass

Georgy

thanks to everyone so far.

Matthias Janes
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
7330
by: Gregory | last post by:
Hello, I've managed to build two web pages, one that can display images with associated text data in a table, and one that can resize and display images without the text. I'd like to resize the images as I go, without writing them to disk on the server. Do I need to prepare all of the resized images before I display the data from the select (which is put into an array by php). How can I display a resized image in a table, without writing...
3
3481
by: Dalan | last post by:
At first I was not certain what could cause Access 97 from displaying most jpeg images, but not all. After further testing, it seemed that all original images of less than 275 pixels per inch or less would display, but those close to 300 pixels/inch or greater would not (MS Access cannot recognize the file format xxx.jpg). The larger, original images were scanned and saved as .bmp (at 300 dpi producing a 15MB file). Then the images were...
2
5228
by: marvin | last post by:
Hi, I am trying to display images in a repeater from a SQL database and do some transformations on the image prior to displaying them (such as thumbnail with a shadow). The problem is I can't seem to get the data passed to the handler. The following is the code that I have so far. In the ViewPics.aspx file I have...
5
2154
by: ljuljacka | last post by:
I'm trying to display resized images. Locations of images are fetched from database. The problem is that with the following code, I get only the first image displayed: <?php header('Content-type: image/jpeg'); $link = mysql_connect('localhost', 'root', ''); if (!$link) {
4
2676
by: redpears007 | last post by:
Hi Again, Throwing this one out to you again as i am not getting anywhere and can find little to no information out there. I am currently displaying images (Jpegs) in access via the routine set up in the article http://support.microsoft.com/kb/285820/en-us. It works fine if the image is under 1000x1000 pixels. It is set up so the user can double click to open the image in its host application.
1
4213
by: littlealex | last post by:
IE6 not displaying text correctly - IE 7 & Firefox 3 are fine! Need some help with this as fairly new to CSS! In IE6 the text for the following page doesn't display properly - rather than being aligned to the top, along with the slideshow and link buttons, you have to scroll down to see the text - how can I make IE6 display correctly? http://geekarama.co.uk/new_home.html here is the code for new_home.html and following that the CSS...
4
1686
by: shahidrasul | last post by:
i display a pic on picture box and then i want to display another pic after some seconds but problem is that first image is not displaying only display 2nd image 1... display first picture from database such as pbThumbImage.Image = new Bitmap(new MemoryStream(objEmployee.Picture)); 2... and then get the reference of current main thread Thread main = Thread.CurrentThread; Thread.Sleep(5000);
6
2188
by: Jeff | last post by:
hi asp.net 2.0 I have a image (.jpeg) stored in sql server 2005 and now I want to display it on a webpage. So I created a webpage (Image.aspx) which just writes the buffer data to the Response object. On Default.aspx I use this Image.aspx for displaying the image, but no image
3
7722
by: mvijayrkumar | last post by:
Hi to all.... Guys pls help me..... I have an image issue in RLDC while hosting my project on server.The image displays or works fine with the local system.But when hosted on server,both the images(One coming from DataSet and another from my project image folder) not displaying. Both images are having Type property External and the Values are given correspondingly.ie The One coming from Image Folder;using the Report Parameter ,the...
0
8802
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9314
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9175
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9075
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7953
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6634
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5948
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4464
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4726
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.