乐愚社区Beta

 编程语言  >  Python-将一张图切割九宫格图

Python-将一张图切割九宫格图

Walker  管理员   L12  • 2020-08-29 • 回复 0 • 只看楼主举报    

九宫格主体是一个 3x3 的正方形矩阵 有9张对应的图片组成
本次利用 Python 的 PIL 库 将一张非正方形的矩阵,切割重组成9张正方形矩阵图
代码如下:

import os
from tkinter import filedialog
from PIL import Image
from future.moves import tkinter

def open_img():
    """
    打开图片
    :return:
    """
    root = tkinter.Tk()  # 创建一个Tkinter.Tk()实例
    root.withdraw()  # 将Tkinter.Tk()实例隐藏
    default_dir = r"文件路径"
    file_path = filedialog.askopenfilename(title=u'选择文件', initialdir=(os.path.expanduser(default_dir)))
    if len(file_path) != 0:
        image = Image.open(file_path)
        fill_image(image)
    else:
        SystemExit()

def fill_image(img):
    """
    将图片填充为正方形
    :param img: 图片
    :return:
    """
    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:  # 原图宽大于高,则填充图片的竖直维度
        # (x,y)二元组表示粘贴上图相对下图的起始位置
        new_image.paste(img, (0, int((new_image_length - height) / 2)))
    else:
        new_image.paste(img, (int((new_image_length - width) / 2), 0))
    cut_image(new_image)

def cut_image(img):
    """
    切图
    :param img: 填充成方形后的图片
    :return:
    """
    width, height = img.size
    item_width = int(width / 3)
    box_list = []
    for i in range(0, 3):  # 两重循环,生成9张图片基于原图的位置
        for j in range(0, 3):
            box = (j * item_width, i * item_width, (j + 1) * item_width, (i + 1) * item_width)
            box_list.append(box)
 
    img_list = [img.crop(box) for box in box_list]
    save_images(img_list)

def save_images(img_list):
    """
    保存切割完成的图片
    :param img_list: 切割后的图片列表
    :return:
    """
    index = 1
    files_path = 'Pic'
    # 若文件夹不存在,则创建
    if not os.path.exists(files_path):
        os.makedirs(files_path)
 
    for img in img_list:
        img.save('./Pic/' + str(index) + '.png', 'PNG')
        index += 1
    print('完成')

if __name__ == '__main__':
    open_img()

还没注册帐号?快来注册社区帐号,和我们一起嗨起来!
关于本社区

集各类兴趣爱好于一身的轻量化交流社区,在此您可以和他人一起分享交流您觉得有价值的内容,社区鼓励大家发表原创内容,为社区添砖加瓦!

发帖奖励 → 社区版规 → 招聘版主 →
推荐版块
扫描二维码下载社区APP
回到顶部