<<返回python首页 python

《Python 应用案例》

Python实现朋友圈的九宫格图片

Python实现九宫格图片

作者:Python小二 转载自微信公号:Python小二

原文链接:https://mp.weixin.qq.com/s/PcvL4QKW4wWNPnTL9hboPw

大家应该经常在朋友圈看到有人发九宫格图片,其实质就是将一张图片切成九份,然后在微信中一起发这九张图即可。

说到切图,Python 就可以实现,主要用到的 Python 库为 Pillow,安装使用 pip install pillow 即可,切图的主要步骤如下:

  • 打开要处理的图片
  • 判断打开的图片是否为正方形
  • 如果是正方形,就进行九等分,如果不是正方形,先用白色填充为正方形,再进行九等分
  • 保存处理完的图片

实现代码

Pillow库安装

pip3 install pillow -i https://pypi.tuna.tsinghua.edu.cn/simple

主要实现代码如下:

import os
from PIL import Image
from IPython.display import Image as ImageOpen

# 填充新的 image
def fill_image(image):
    width, height = image.size
    _length = width
    if height > width:
        _length = height
    new_image = Image.new(image.mode, (_length, _length), color='white')
    if width > height:
        new_image.paste(image, (0, int((_length - height) / 2)))
    else:
        new_image.paste(image, (int((_length - width) / 2), 0))
    return new_image

# 裁剪 image
def cut_image(image):
    width, height = image.size
    _width = int(width / 3)
    box_list = []
    for i in range(0, 3):
        for j in range(0, 3):
            box = (j * _width, i * _width, (j + 1) * _width, (i + 1) * _width)
            box_list.append(box)
            image_list = [image.crop(box) for box in box_list]
    return image_list

# 将 image 列表的里面的图片保存
def save_images(image_list, res_dir):
    index = 1
    if not os.path.exists(res_dir):
        os.mkdir(res_dir)
    for image in image_list:
        new_name = os.path.join(res_dir, str(index) + '.png')
        image.save(new_name, 'PNG')
        index += 1
    print('图片保存完毕!')

if __name__ == '__main__':
    image = Image.open('/share/image/jiugongge.jpg')
    image = fill_image(image)
    image_list = cut_image(image)
    save_images(image_list, 'imgs')

原图

Python实现九宫格图片

查看被分割的图片,一共九张,从数字1至9保存命名

ImageOpen(filename = "/root/imgs/7.png")

效果图:

Python实现九宫格图片

移动端设备除iPad Pro外,其它移动设备仅能阅读基础的文本文字。
建议使用PC或笔记本电脑,浏览器使用Chrome或FireFox进行浏览,以开启左侧互动实验区来提升学习效率,推荐使用的分辨率为1920x1080或更高。
我们坚信最好的学习是参与其中这一理念,并致力成为中文互联网上体验更好的学练一体的IT技术学习交流平台。
您可加QQ群:575806994,一起学习交流技术,反馈网站使用中遇到问题。
内容、课程、广告等相关合作请扫描右侧二维码添加好友。

狐狸教程 Copyright 2021

进入全屏