Python Multimedia
上QQ阅读APP看书,第一时间看更新

Reading and writing images

To manipulate an existing image, we must open it first for editing and we also require the ability to save the image in a suitable file format after making changes. The Image module in PIL provides methods to read and write images in the specified image file format. It supports a wide range of file formats.

To open an image, use Image.open method. Start the Python interpreter and write the following code. You should specify an appropriate path on your system as an argument to the Image.open method.

>>>import Image
>>>inputImage = Image.open("C:\\PythonTest\\image1.jpg")

This will open an image file by the name image1.jpg. If the file can't be opened, an IOError will be raised, otherwise, it returns an instance of class Image.

For saving image, use the save method of the Image class. Make sure you replace the following string with an appropriate /path/to/your/image/file.

>>>inputImage.save("C:\\PythonTest\\outputImage.jpg")

You can view the image just saved, using the show method of Image class.

>>>outputImage = Image.open("C:\\PythonTest\\outputImage.jpg")
>>>outputImage.show()

Here, it is essentially the same image as the input image, because we did not make any changes to the output image.