如果系统中没有安装Pillow包,安装:
pip install pillow
# 导入pillow from PIL import Image # 加载原始图片 img = Image.open("lena.jpg") # 从左上角开始 剪切 200*200的图片 img2 = img.crop((0, 0, 200, 200)) img2.save("lena2.jpg")
从右下角开始(200*200)
从中心开始(100*150)
half_the_width = img.size[0] / 2 half_the_height = img.size[1] / 2 img4 = img.crop( ( half_the_width - 50, half_the_height - 75, half_the_width + 50, half_the_height + 75 ) ) img4.save("lena4.jpg")
把图片填充为正方形
longer_side = max(img4.size) horizontal_padding = (longer_side - img4.size[0]) / 2 vertical_padding = (longer_side - img4.size[1]) / 2 img5 = img4.crop( ( -horizontal_padding, -vertical_padding, img4.size[0] + horizontal_padding, img4.size[1] + vertical_padding ) ) img5.save("lena5.jpg")