The image library provides useful functions for displaying and manipulating JPEG and PNG graphic files. To use it, you need following in your program:
from image import *
This defines the Image class. The Image class is similar to the Icon class (seen in the GUI library), except an Image:
- has its own window,
- can be manipulated at the individual pixel level, and
- can be written/saved to an external file.
Function | Description |
Image(filename) | Reads in a .jpg or .png file called filename (a string) and shows an image. It returns the image, so it should be stored in a variable, e.g., img = Image(“sunset.jpg”) |
Image(width, height) | Returns an empty (blank) image with provided width and height. It returns the image, so it should be stored in a variable, e.g., img = Image(200, 300) |
One an image has been created, the following functions are available:
Function | Description |
img.show() | Displays the image img in a window. |
img.hide() | Hides the image window. |
img.getWidth() | Returns the width of image img. |
img.getHeight() | Returns the height of image img. |
img.getPixel(col, row) | Returns this pixel’s RGB values (a list, e.g., [255, 0, 0]), where col is the image column, and row is the image row. The image origin (0, 0) is at top left. |
img.setPixel(col, row, RGBlist) | Sets this pixel’s RGB values, e.g., [255, 0, 0], where col is the image column, and row is the image row. The image origin (0, 0) is at top left. |
img.getPixels() | Returns all the pixels in this image in a list of rows. Each row is a list of pixels for that row. Each pixel is a list of RGB values, e.g., [255, 0, 0]. I.e., the image’s top-left pixel is at index [0][0]. |
img.setPixels(pixels) | Sets all the pixels in this image, where pixels in a list of rows. Each row is a list of pixels for that row. Each pixel is a list of RGB values, e.g., [255, 0, 0]. I.e., the image’s top-left pixel is at index [0][0]. |
img.write(filename) | Writes image img to the .jpg or .png filename. |