基于Python实现图片一键切割九宫格的工具

 更新时间:2023年03月22日 09:05:26   作者:徐浪老师  
有时候发微博时候,需要裁切图片为九宫格,但是ps或者其他工具都太麻烦。本文就来用Python编写一个一键切割九宫格的工具,希望对大家有所帮助

有时候发微博时候,需要裁切图片为九宫格,但是ps或者其他工具都太麻烦,这里写一个python一键切割九宫格的工具,以供大家学习和使用!

实现代码

"""
 1.将一张图片填充为正方形
 2.将文字加到方形图片上
 3.讲图片切为9张图并存储
"""
import os
from tkinter import filedialog
from PIL import Image
from future.moves import tkinter
# 填充文字的库
import PIL
from PIL import ImageFont,Image,ImageDraw

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))

    # 图片上写上文字
    # 设置字体,如果没有,也可以不设置
    font = ImageFont.truetype(r"C:\Windows\Fonts\STHUPO.TTF", 50)
    datas='V:xlzcm88或xlzcm66'
    bytedatas=datas.encode('UTF-8')
    draw = ImageDraw.Draw(new_image)
    draw.text((0,new_image.size[1]/2), u'V:xlzcm88或xlzcm66', font=font)

    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()

方法补充

除了上文的方法,小编还给大家整理了其他图片切割成九宫格的方法,希望对大家有所帮助

# -*- coding: utf-8 -*-
 
from PIL import Image
import sys
 
 
# 将图片填充为正方形
def fill_image(image):
    width, height = image.size
    # 选取长和宽中较大值作为新图片的
    new_image_length = width if width > height else height
    # 生成新图片[白底]
    new_image = Image.new(image.mode, (new_image_length, new_image_length), color='white')
    # 将之前的图粘贴在新图上,居中
    if width > height:  # 原图宽大于高,则填充图片的竖直维度
        new_image.paste(image, (0, int((new_image_length - height) / 2)))  # (x,y)二元组表示粘贴上图相对下图的起始位置
    else:
        new_image.paste(image, (int((new_image_length - width) / 2), 0))
    return new_image
 
 
# 切图
def cut_image(image):
    width, height = image.size
    item_width = int(width / 3)
    box_list = []
    # (left, upper, right, lower)
    for i in range(0, 3):
        for j in range(0, 3):
            # print((i*item_width,j*item_width,(i+1)*item_width,(j+1)*item_width))
            box = (j * item_width, i * item_width, (j + 1) * item_width, (i + 1) * item_width)
            box_list.append(box)
 
    image_list = [image.crop(box) for box in box_list]
 
    return image_list
 
 
# 保存
def save_images(image_list):
    index = 1
    for image in image_list:
        image.save('./output/' + str(index) + '.jpg')
        index += 1
 
 
if __name__ == '__main__':
    file_path = "./output/girl.jpg"
    image = Image.open(file_path)
    image.show()
    image = fill_image(image)
    image_list = cut_image(image)
    save_images(image_list)
 

到此这篇关于基于Python实现图片一键切割九宫格的工具的文章就介绍到这了,更多相关Python图片切割九宫格内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python time库的时间时钟处理

    Python time库的时间时钟处理

    这篇文章主要介绍了Python time库的时间时钟处理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-05-05
  • 浅谈Pycharm的项目文件名是红色的原因及解决方式

    浅谈Pycharm的项目文件名是红色的原因及解决方式

    这篇文章主要介绍了浅谈Pycharm的项目文件名是红色的原因及解决方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06
  • 深度辨析Python的eval()与exec()的方法

    深度辨析Python的eval()与exec()的方法

    这篇文章主要介绍了深度辨析Python的eval()与exec()的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-03-03
  • python文件排序的方法总结

    python文件排序的方法总结

    在本篇内容里小编给各位整理的是一篇关于python文件排序的方法总结,有需要的朋友们可以参考下。
    2020-09-09
  • Pycharm+Python工程,引用子模块的实现

    Pycharm+Python工程,引用子模块的实现

    这篇文章主要介绍了Pycharm+Python工程,引用子模块的实现,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-03-03
  • Python数据结构之栈详解

    Python数据结构之栈详解

    栈和队列是在程序设计中常见的数据类型,从数据结构的角度来讲,栈和队列也是线性表,是操作受限的线性表。本文将详细介绍一下Python中的栈,感兴趣的可以了解一下
    2022-03-03
  • TensorFlow实现指数衰减学习率的方法

    TensorFlow实现指数衰减学习率的方法

    这篇文章主要介绍了TensorFlow实现指数衰减学习率的方法,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-02-02
  • python游戏实战项目之智能五子棋简易版

    python游戏实战项目之智能五子棋简易版

    利用Python实现智能五子棋,实现之后发现我玩不赢它!本篇为你带来用python编写的五子棋小游戏,文中给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值
    2021-09-09
  • Python3监控疫情的完整代码

    Python3监控疫情的完整代码

    这篇文章主要介绍了Python3监控疫情的完整代码,代码简单易懂,非常不错具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-02-02
  • 基于PyTorch的permute和reshape/view的区别介绍

    基于PyTorch的permute和reshape/view的区别介绍

    这篇文章主要介绍了基于PyTorch的permute和reshape/view的区别介绍,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06

最新评论