python制作九宫图

"""
思路:
1、转换为正方形
2、切割小图片的尺寸要保持一致
3、计算小图片的坐标值
4、图片有几个坐标 —— 4个
"""
from PIL import Image

# 1、填充图像为正方形
def fill_image(img):
    width, height = img.size
    # 原图 分割之后的图
    # 选择最大的宽和高 作为新图像的宽和高
    new_image_length = width if width > height else height
    # 创建新的图像
    new_image = Image.new(img.mode, (new_image_length, new_image_length), color='white')
    if width > height:
        # 拼贴、粘贴
        new_image.paste(img, (0, int(new_image_length - height)/2))
    else:
        new_image.paste(img, (int((new_image_length - width) / 2), 0))
    return new_image


# 2、分割、裁剪图像
def split_image(img):
    width, height = img.size
    item_width = int(width/3)
    box_list = []
    # 循环嵌套
    for x in range(0, 3):
        for y in range(0, 3):
            # 左下右上 - 4元组坐标
            box = (y*item_width, x*item_width, (y+1)*item_width, (x+1)*item_width)
            box_list.append(box)
    # 裁剪
    img_list = [img.crop(box) for box in box_list]
    return img_list


# 3、保存裁剪之后图像
def save_image(img_list):
    index = 1
    for img in img_list:
        img.save('picture/'+str(index)+'.png')
        index += 1


if __name__ == '__main__':
    # 打开一张图片
    image = Image.open('picture/gakki.png')
    image = fill_image(image)
    img_list = split_image(image)
    save_image(img_list)

运行后的9张图片:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值