9

使用Python Pillow库生成九宫格图片

 3 years ago
source link: https://zhuanlan.zhihu.com/p/363074719
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

使用Python Pillow库生成九宫格图片

公号:python大数据分析

相信很多人看到过九宫格图片,一张完整的大图被分割成九张小图,在朋友圈和微博里一度成为流行。

v2-22b5ae53653b0833447b68adcedc8b29_720w.jpg

相比完整的大图,九宫格图文增添了一丝趣味和精致,也显得更有创意。

制作九宫格图片的工具有很多,下文用Python的PIL库来实现图片的九宫格切分。

切分有以下要求:

1、不管原图尺寸如何,切出来的九张图拼在一起后,需是一张正方形大图

2、尽可能不改变原图的清晰度

3、对切分后的九张图用数字序号命名,方便朋友圈或微博上传

申明下,这个小脚本实用性见仁见智,主要是方便初学者练习语法并建立兴趣。

如果你有批量处理图片的需求,那么这个脚本或许对你有很大帮助。

'''
朋友圈九宫格图片制作
工具库:Pillow
'''

# encoding=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)))
    else:
        new_image.paste(image, (int((new_image_length - width) / 2), 0))
    return new_image


# 第二步:将图片切割成九宫格
def cut_image(image):
    width, height = image.size
    # 一行放3张图
    item_width = int(width / 3)
    box_list = []
    for i in range(0, 3):
        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)
    image_list = [image.crop(box) for box in box_list]
    return image_list


# 第三步:保存图片
def save_images(image_list,save_path):
    index = 1
    for image in image_list:
        image.save(save_path +str(index) + '.png', 'PNG')
        index += 1


if __name__ == '__main__':
    file_path = "e:\\图片\\新垣结衣.jpg"
    save_path = "e:\\图片\\九宫格\\"
    image = Image.open(file_path)
    image = fill_image(image)
    image_list = cut_image(image)
    save_images(image_list)
    print("{}张图片全部生成".format(len(image_list)))

上面不到50行代码,便实现了对图片的九宫格切分。你可以复制代码到本地,只需添加原图和生成图的路径,就能执行代码并得到结果。

我们看下生成好的九张图:

v2-f332e514da5e9a4885fa36b51137797a_720w.jpg

再保存到手机里,发朋友圈时,依次按1~9顺序上传图片即可。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK