Hi,
welcome to this new post about programming with Python.
Today, we are going to talk about cropping images. To do it, we will use PIL (Python Images Library), a module to manipulate images with Python. Well, we will use pillow (pip install pillow from the cmd – press the window button + R and then type in cmd and Enter, in the cmd window that will appera write pip install pillow), a fork of PIL, that is better mantained.
Window button + R
Say we got this image of a sprite animation that contains, in one file, 6 different sprites for the animation.
We want to get the first image.
This is the code to do it:
- open the image (Image.open)
- get width w and height h of it (im.size)
- crop the first (im.crop((area))
- the area is a tuple of the coordinates of the top left corner and bottom right one
- save the cropped image
from PIL import Image im = Image.open("sprite.png") w, h = im.size im1 = im.crop((0, 0, w // 6, h)) im1.save("01.png")
This is the result
As we want to automate stuffs, lets make a code that gives us all the images of the animation in a png file for each one of them, in separate files.
Abstracting to get all the images separated
Here is the way to split the images
from PIL import Image def crop(filename, number): im = Image.open(filename) w, h = im.size unit = w // 6 for n in range(number): im1 = im.crop((unit * n, 0, unit * (n + 1), h)) im1.save(filename[:-4] + str(n + 1) + ".png") crop("sprite.png", 6)
Live coding video about cropping images with PIL and Python
Utilities