若是系統中沒有安裝Pillow包,安裝:sublime-text
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)ide
從中心開始(100*150)spa
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")
把圖片填充爲正方形code
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")