Manipulating images with PIL

In order to use PIL, we will first need to install it. The version which I will be using is available on pip and can be installed with the following command:

pip install pillow

PIL provides multiple ways of resizing an image. Two possible methods we could use in our application are resize and thumbnail.

The resize method will alter an image to be the exact size provided to the method (as a two-tuple of width and height). On the other hand, the thumbnail method will preserve the aspect ratio of an image, preventing skew, resizing the larger dimension of the image to the provided maximum size, and keeping the smaller dimension at the same ratio. 

For my implementation of this application, I will be using the thumbnail method to resize avatars, as it will make any rectangular images look nicer when scaled down. If you would prefer to keep images as squares, you may replace the calls to thumbnail with resize to achieve this.

With PIL installed, head back over to your avatarwindow.py file and edit the choose_image function, as follows:

from PIL import Image
...

def choose_image(self):
image_file = filedialog.askopenfilename(filetypes=self.image_file_types)

if image_file:
avatar = Image.open(image_file)
avatar.thumbnail((128, 128))
avatar.save(avatar_file_path, "PNG")

img_contents = ""

After the user selects their image file, we want to overwrite the file stored at our avatar_file_path with a scaled-down version. To do this, we use the open method of PIL's Image class, passing it the path to their chosen image file.

Once we have this image, we use the thumbnail method to scale it down, passing it a two-tuple of (128, 128) to act as the maximum width and height of the new image.

To save this scaled image over the one in our avatar_file_path, we call the save method. We pass this method the path at which to save the image and the format, in our case, PNG.

The rest of the method then continues as normal.

Run your application once again, open the avatar window, and choose a large image. You should now see that your chosen avatar fits nicely inside the window.

The last thing we need to address with our chat application is the management of users. Currently, every user of the system is available to chat with every other user. This is not ideal, since people will be able to talk to complete strangers. We need to add a way for users to add other users as friends, thus giving them the ability to talk to one another.

While we are at it, we should also allow users to block other users, should they wish to cease contact.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset