使用pthon将图片裁剪成指定正方形大小
时间: 2023-06-04 13:04:40 浏览: 72
可以使用PIL库来实现这个功能。具体步骤如下:
1. 使用PIL库打开图片:`img = Image.open('path/to/image.jpg')`
2. 获取原始图片的宽和高:`width, height = img.size`
3. 计算要裁剪的区域:如果宽大于高,裁剪出中心部分的正方形区域;如果高大于宽,同样裁剪出中心部分的正方形区域。具体代码如下:
```
if width > height:
left = (width - height) / 2
right = (width + height) / 2
top = 0
bottom = height
else:
left = 0
right = width
top = (height - width) / 2
bottom = (height + width) / 2
region = img.crop((left, top, right, bottom))
```
4. 将裁剪后的区域重新调整为指定大小:`square_img = region.resize((size, size), Image.ANTIALIAS)`
5. 保存新图片:`square_img.save('path/to/new_image.jpg')`