How to Get Python to Get a Picture Output
Python is a general purpose programming language for web and desktop software development. Its flexibility makes it a perfect choice to implement code in large projects that perform a variety of tasks, or serving as a "glue" language that that performs certain tasks for other programs. For example, Python can take the image output of a program saved to disk and manipulate it. It can then store the new image and delete the old one, leaving an image for other programs to use.
Instructions
-
-
1
Import the necessary modules. In the case of this program, only one module is really necessary: the Python Image Library, or "PIL," module, available at pythonware.com/products/pil/index. The PIL module allows the programmer to create Image objects that can store image information. The following example shows how to import the module:
>>>from PIL import Image
This program only imports the Image package from PIL, not the entire PIL module:
-
2
Find the directory in which the image output files are located. For example, if another program generates ".jpg" images and stores them in the "/home" directory, then the Python program needs to know that, in order to gather those images. The programmer then creates an Image object to fetch the image. In this example, Python gets the image "party.jpg" from "/home" and stores it in an Image object:
>>>pic = Image.open("/home/party.jpg")
-
-
3
Delete the old file and replace it with the new file. Assuming that the Python script modifies the image in some way, it can now remove the older file and replace it with the most current version. The programmer accomplishes this through the "remove" function in the "os" module. The following code example shows the full program, which gathers image data, manipulates it, and replaces an old file with a new file:
>>>import os
>>>from PIL import Image
>>>pic = Image.open("/home/party.jpg")
>>>pic.resize(500, 500) // resizes the image to 500 pixels by 500 pixels
>>>pic.save("/home/party_new.jpg")
>>>os.remove("/home/party.jpg")
-
1