Last Updated on 2021-05-22 by Clay
When I was implementing my side project today, I need to crop a lot of images. Fortunately, the size of image is all 1920 x 1080, so I can crop the fixed area.
As more and more image process I experimented, I like package "Pillow" more than before. Maybe one day I will write a more detailed note of it, but today I only want to record how to crop the image.
Pillow
Pillow is a Python package for processing image. If you are using for the first time, you need to use the following command to install this package:
pip3 install Pillow
When you done, we can use Python to call the package Pillow.
Suppose I have a picture like this:

And I want to crop the monster of the center area, and save to a new picture.
First, you can open "mspaint.exe" or other similar applications to check the (x, y) coordinates.

The position of the mouse will be displayed in the lower left corner, so we can view the coordinates of the range we want to capture.

Like this.
And this is my sample code:
# -*- coding: utf-8 -*- import os import re from PIL import Image picList = os.listdir('pic') for pic in picList: if '01.png' not in pic: continue image = Image.open('pic/{}'.format(pic)) # Crop newImage = image.crop((780, 310, 1080, 610)) newImage.show() exit()
First, we need to use "from PIL import Image" to import the function we want to use. and I traverse all the files in the "pic" folder and saved them in the "picList", and load them.
# Crop newImage = image.crop((780, 310, 1080, 610)) newImage.show()
You can understand it like this:
image.crop((x, y, dx, dy))
Output:

Finally, we saved our picture.
All code:
# -*- coding: utf-8 -*- import os import re from PIL import Image picList = os.listdir('pic') for pic in picList: if '01.png' not in pic: continue image = Image.open('pic/{}'.format(pic)) # Crop newImage = image.crop((780, 310, 1080, 610)) # Save newFileName = re.sub('01.png', '', pic) newImage.save('Icons/{}.png'.format(newFileName), quality=100)
Output:

You're done!
References
- https://pillow.readthedocs.io/en/stable/reference/Image.html
- https://stackoverflow.com/questions/20361444/cropping-an-image-with-python-pillow