Working with Images

Before you start, find an image to work with.  It will be easiest if you choose a smaller image to start with. One less than 400 x 400 pixels would be best.

Lets look at some of the commands you can use in Jython to work with images.  You can type these directly into the Command (bottom) Window.

 

 pickAFile()

        pickAFile() Opens a file selection box and returns a string giving the filename you select

In the command window try out:  print pickAFile()

It will output the path and filename of the file you select.

 

 

makePicture()

makePicture(pickAFile())

will identify your file as a picture (but it won't show it yet!)    

print makePicture(pickAFile())

will print out the file name with path, and the height and width of your picture

So we have now made the file into a picture, but we can't see it yet.  To show it we use the command show()

 

show()    

show(makePicture(pickAFile()))

will show the picture stored in the storage location called mypicture

 

Picking and Showing your Picture in one Command

Rather than typing all those commands each time we can create a picture showing recipe (function)

You can assign the file picked to a variable to store it for later use. For example

myfile=pickAFile()

print myfile

will print the path and name of the selected file.

 

In the top (program) window, type the following (take care to indent the lines as shown below)

def pickAndShow():

myfile = pickAFile()
mypicture = makePicture(myfile)
show(mypicture)

Once you’ve typed in your recipe you can load it. Click the Load button. You will be prompted to Save it first.

Now in the bottom (command) window, type pickAndShow()

The file you select should be shown in an image window.

 

 

Common Bug : Windows filenames and backslashes

Windows uses backslashes as file delimiters. Python uses some backslash and character combinations to have special meanings, as we’ll talk more about later. For example, ’\n’ means the same thing as the Enter or Return key.

Those combinations can occur naturally in Windows filenames. To avoid having Python misinterpret those characters, you have to type your filenames with an “r” in front, like this:

>>> myfile = r"C:\pictures\beagle.jpg"

>>> print myfile

C:\pictures\beagle.jpg