Resize and crop images with PIL

Resize a single image

To resize an Image with PIl module and Python, you need this code:

from PIL import Image

img = Image.open("myimage.png")
img = img.resize((128, 128), Image.ANTIALIAS)
img.save("myimage_little.png")

Resizing all the images in a folder

from PIL import Image
import glob
import os

lst_imgs = [i for i in glob.glob("*.png")]

# It creates a folder called ltl if does't exist
if not "ltl" in os.listdir():
	os.mkdir("ltl")

print(lst_imgs)
for i in lst_imgs:
	img = Image.open(i)
	img = img.resize((64, 64), Image.ANTIALIAS)
	img.save("ltl\\" + i[:-4] + "_ltl.png")


print("Done")
os.startfile("ltl")

Live coding: resize all images in a folder with Python and PIL

Crop images with PIL

To crop images you can, instead use the crop method:

from PIL import Image
import glob
import os

lst_imgs = [i for i in glob.glob("*.png")]

# It creates a folder called ltl if does't exist
folder = "crp"
if folder not in os.listdir():
    os.mkdir(folder)

print(lst_imgs)
area = (0, 0, 68, 60)
for i in lst_imgs:
    img = Image.open(i)
    img = img.crop(area)
    # img = img.resize((64, 64), Image.ANTIALIAS)
    img.save(folder + "\\" + i[:-4] + "_" + folder + ".png")


print("Done")
os.startfile(folder)

 

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.