List Info

Thread: Newbie looking for help uploading images, Python Image Library




Newbie looking for help uploading images, Python Image Library
country flaguser name
United States
2007-10-17 04:13:21
Hello all,

I have been banging my brains against this for a few days
and have
finally thrown in the towel.

I am not a programmer by trade (which I simply state before
anyone
sees the state of my code .

I am trying to write a simple little
cherrypy/cherrytemplate/sqlite
based app that will display pictures of toys from the toy
library my
wife works at.

Even for a rank beginner like myself it was simple to get
the page to
display the toys loaded in to the database.  My problem is
adding new
toys. More specifically manipulating images after they are
uploaded.

I have copied in the offending code below. What I am trying
to do is
have the Python Image Library resize the image to a large
size and a
small size before saving to one of two directories.. I have
tried may
google found results to get Image.open to open the file,
treating the
image<x> as a 'file', encapsulating the image in
StringIO like
Image.open(StringIO(image0)) etc and nothing seems to work.
I feel I
must be missing some obvious as I suspect that the images
are not
being uploaded at all.

As a work around I could save the files to disk first and
reload them
with Image.open but I would really like to do all the
manipulation
first before saving.

Any help would be appreciated.

Thanks.

Leslie

EXTRACT FROM tldb.py:
import os #save uploaded images
import cherrypy # the page serving software
import Image # resize images on the fly
import StringIO # allows access by Image to the uploaded
images
without writing to disk
from pysqlite2 import dbapi2 as sqlite #access sqlite
database
from cherrytemplate import renderTemplate # use the
cherrytemplate
engine

<...>

	def confirmadd(self, pub_id, name, type, desc, ctype,
pieces=1,
image0=None, image1=None, image2=None, image3=None,
image4=None):

		errors=[]
		message=[]
		imageSaved=[False, False, False, False, False]
		imageName=[None, None, None, None, None]

		smwidth=64
		smheight=48
		lgwidth=320
		lgheight=240

		currentdir = os.curdir
		imagepath =
os.path.join(os.getcwd(),"images","tempimg&qu
ot;)
		imageList=[image0,image1,image2,image3,image4]

		for x in range(len(imageList)):
			imageFileName=pub_id+"_0"+str(x)+".jpg&quo
t;
			try:
				image=Image.open(StringIO(imageList[x]))
				try:
					lgimage =
image.resize((lgwidth,lgheight),Image.ANTIALIAS)
					lgimagepath=os.path.join("images","lgtoy
images",imageFileName)
					try:
						lgimage.save(lgimagepath)
					except:
						errors.append("Resize of
image"+str(x)+" failed")
						imageSaved[x]=False
						break

					smimage = image.resize((smwidth,
smheight),Image.ANTIALIAS)
					smimagepath=os.path.join("images","smtoy
images",imageFileName)
					try:
						smimage.save(smimagepath)
					except:
						errors.append("Resize of
image"+str(x)+" failed")
						imageSaved[x]=False
						break
				except:
					errors.append("Resize of image"+str(x)+"
failed")
					imageSaved[x]=False
					break
				imageSaved[x]=True
			except:
				errors.append("Image"+str(x)+" was a
complete faliure, was it even
an image?")

		if (imageSaved[0]):
			imageName[0]=pub_id+"_00.jpg"
		if (imageSaved[1]):
			imageName[1]=pub_id+"_01.jpg"
		if (imageSaved[2]):
			imageName[2]=pub_id+"_02.jpg"
		if (imageSaved[3]):
			imageName[3]=pub_id+"_03.jpg"
		if (imageSaved[4]):
			imageName[4]=pub_id+"_04.jpg"

		con = sqlite.connect("data/tldb.sqlite")
		cur = con.cursor()
		try:
			cur.execute("INSERT INTO tblToys (pub_id, name,
type, description,
pieces, container, image0, image1, image2, image3, image4)
VALUES
(?,?,?,?,?,?,?,?,?,?,?)",(pub_id, name, type, desc,
pieces, ctype,
imageName[0], imageName[1], imageName[2],imageName[3],
imageName[4],))
			message.append("Added ok!")
			con.commit()
		except:
			con.rollback()
			errors.append("Updating the database failed. It
could just be
becasue it was busy doing something else or maybe the Toy
Number
selected is already in use.")
		cur.close()
		con.close()
		return renderTemplate(file='templates/confirmadd.html')
	confirmadd.exposed=True

END OF tldb.py EXTRACT

ADD.HTML
<h1>Add a New Toy</h1>
<form action="confirmadd"
method="post"
enctype="multipart/form-data">
	Toy Number: <input type="text"
name="pub_id"/></br>
	Toy Name: <input type="text"
name="name"/></br>
	Toy Type: <select name="type">
			<py-for="row in toyTypes">
				<option
value="<py-eval="str(row[0])"/>"&g
t;<py-eval="str(row[1])"/></
option>
			</py-for>
		</select></br>
	Description: <textarea row="10"
cols="50"
name="desc"></textarea></
br>
	Container: <select name="ctype">
			<py-for="row in containers">
				<option
value="<py-eval="str(row[0])"/>"&g
t;<py-eval="str(row[1])"/></
option>
			</py-for>
		</select></br>
	Pieces: <input type="text"
name="pieces"/></br>
	Image 1: <input type="file"
name="image0"/></br>
	Image 2: <input type="file"
name="image1"/></br>
	Image 3: <input type="file"
name="image2"/></br>
	Image 4: <input type="file"
name="image3"/></br>
	Image 5: <input type="file"
name="image4"/></br>
	<input type="submit" value="Add
Toy"/>

</form>


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the
Google Groups "cherrypy-users" group.
To post to this group, send email to cherrypy-usersgooglegroups.com
To unsubscribe from this group, send email to
cherrypy-users-unsubscribegooglegroups.com
For more options, visit this group at h
ttp://groups.google.com/group/cherrypy-users?hl=en
-~----------~----~----~----~------~----~------~--~---


: Newbie looking for help uploading images, Python Image Library
country flaguser name
United States
2007-10-21 04:48:37
To save anyone else the pain I have gone through to get this
to work,
here is the working line you need:

image=Image.open(StringIO.StringIO(uploadedFile.file.read())
)

The reason is when an image is uploaded cherrypy (or pythons
cgi
thingy) turns the image in to an object which interestingly
has stored
the actaul name of the uploaded file, the name you gave it
from the
form and the file.

So to access the IMAGE DATA you need to access
uploaded.file
To READ all the IMAGE DATA in one go you need to call the
def
uploaded.file.read()

Now you have the IMAGE DATA, as a string. The Python Image
Library(PIL) needs a little help to 'open' the string. So
you need the
following:

StringIO.StringIO(uploadedFile.file.read())

Finally put it all together with the usual PIL stuff and you
get the
line above.

Either this is blindingly obvious to everyone on the
internet (except
me) or no one has tried to tie cherrypy's file upload to the
PIL,
neither of which seem to be realistic assumptions 

At any rate I hope this helps someone else. The information
to do this
is all out there but if it was a jigsaw puzzle you'd need to
sand off
a few of the knobbly bits from the instructions to get it
all to fit.


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the
Google Groups "cherrypy-users" group.
To post to this group, send email to cherrypy-usersgooglegroups.com
To unsubscribe from this group, send email to
cherrypy-users-unsubscribegooglegroups.com
For more options, visit this group at h
ttp://groups.google.com/group/cherrypy-users?hl=en
-~----------~----~----~----~------~----~------~--~---


[1-2]

about | contact  Other archives ( Real Estate discussion Medical topics )