Opening an image

In this section, we will use use PIL and a library called tkinter to select an image file from your computer.

Firstly, we want to import both of the things we need from these libraries. From PIL we’re going to import the Image class, and from tkinter, we only need to import the filedialog class

from PIL import Image
from tkinter import filedialog

After that, we want to prompt the user to open a file. For this, we can use the filedialog’s askopenfilename() function, like follows. This will give us the name of the file. If you don’t have any images to edit, you can use some of the sample images from here

name = filedialog.askopenfilename()

Now that we have the filename, we can open it with the Image.open function from the library. Because we’re going to change this image around, we want to make sure we first convert it to an “RGB” image. We’ll explain this in a little more detail in the next section.

img = Image.open(name)
img = img.convert("RGB")

Our image is loaded, now we can display it on the screen with the show() function

img.show()