Python: Crop Image
While getting the images is important on it’s own, I ran into the issue of sizing with ActionTiles. The tiles I’m using to display pictures are 2×3, so they are basically a perfect size for a landscape oriented image. And even though I have a tablet that is larger than most, the size of each tile is not huge.
Looking at the weather images, there was a whole lot of border that I really didn’t need. Getting rid of that would really let me see the information I was interested in, and no doubt I’d have other uses for it eventually. So I wrote a second script that assumes the files are in place, named as expected from my download script, and then crops each to a specified size.
For your own images, you will need to know what size you want to crop them to. There are plenty of ways to do that, but if you don’t have a graphics editing program, take a look at GIMP (yes that’s really the name).
You can see that there are a few things going on. First, we assume the image is in the folder the script is running from; if that’s not the case, you obviously will edit the path accordingly. Second, the code defines two points for each image: the top left point, and the bottom right point. With those two defined, it understands what rectangle section will be kept, and then saves it out to the new file name.
In the code below, I then take that a step farther and combine the two images into one single image. There are many reasons to do this, but in my case I was stripping out weather details I wanted from both, and then creating a single image so I didn’t need two tiles to display it.
from PIL import Image
#
# Crop first image
#
img = Image.open("3day1.png")
area = (405, 120, 1450, 675)
cropimg = img.crop(area)
cropimg.save("3day1_small.png")
#
# Crop second image
#
img = Image.open("3day2.png")
area = (405, 670, 1450, 905)
cropimg = img.crop(area)
cropimg.save("3day2_small.png")
#
# Combine both into single image
#
img1 = Image.open("3day1_small.png")
img2 = Image.open("3day2_small.png")
newimg = Image.new("RGB", (1045, 790))
newimg.paste(img1, (0,0))
newimg.paste(img2, (0,555))
newimg.save("3day.png")
NB: You may not have PIL installed on your system. I didn’t. You can use PIP to install Pillow, which will then let you run the above script.
2 thoughts on “Python: Crop Image”