首先需要安装Pillow这个模块
此案例主要的功能:
1.将n张图片分别分割成为等比例大小的16张小图片
2.将原图片压缩为指定大小的小图片
以下是代码:
from PIL import Image
image_index = 1
# 将图片填充为正方形
def fill_image(image):
width, height = image.size
new_image = image
# 判断图片是否是正方形的
if width == height:
new_image.save('./images/' + str(image_index) + '.png', 'PNG')
return new_image
# 将图片填充为正方形
new_length = width
if height > width:
new_length = height
# 生成新的图片,背景为白色
new_image = Image.new(image.mode, (new_length, new_length), color='white')
# 复制旧图片的内容,填充空白部分
if width > height:
new_image.paste(image, (0, int((new_length - height) / 2)))
else:
new_image.paste(image, (int((new_length - width) / 2), 0))
new_image.save('./images/' + str(image_index) + '.png', 'PNG')
return new_image
# 切图
def cut_image(image):
width, height = image.size
item_width = int(width / 4)
item_list = []
# 双重循环,生成16张小图片
for i in range(0, 4):
for j in range(0, 4):
# 竖着切割
image_item = (i * item_width, j * item_width, (i + 1) * item_width, (j + 1) * item_width)
# 横着切割
# image_item = (j * item_width, i * item_width, (j + 1) * item_width, (i + 1) * item_width)
item_list.append(image_item)
# 存储分隔后的图片
image_list = []
for img in item_list:
image_list.append(image.crop(img))
# 保存图片
for index in range(len(image_list)):
image_list[index].save('./images/' + str(image_index) + '_' + str(index + 1) + '.png', 'PNG')
# 修改图片的大小
def change_size(image):
# 将原图片压缩为100*100
out = image.resize((100, 100), Image.ANTIALIAS)
out.save('./images/' + str(image_index) + '.png', 'PNG')
if __name__ == '__main__':
# 所有图片的地址
images_path = ["imgs/zoom.jpg", "imgs/xiyang.jpeg", "imgs/wanxia.jpeg", "imgs/flower.jpg", "imgs/color.jpeg"]
for path in images_path:
image = Image.open(path)
# 填充图片的内容
image = fill_image(image)
# 裁剪图片
cut_image(image)
# 压缩图片
change_size(image)
image_index += 1
处理后的效果(此处仅以一张图片为例展示):
原图片大小:7000*700(此图片为百度随便找的一张图片,如有侵权请联系作者删除)
压缩后的大小100*100
分割后的效果: