用Python拼图发一个高逼格的朋友圈

来源:二胖( 公众号:大数据前沿)   链接:

https://mp.weixin.qq.com/s/bnj5oOdL7iDEmIDlA8h8EA

除了可以处理规整的正方形图片,还可以处理非规则的图片。比如下面这张宽度远大于高度的图片,怎么处理呢?

很简单,取宽和高之间的较大值,然后填充白色,就可以构造出一张正方形的图片啦。


 

当然,想把一张图片做成这样子也很容易啦,现在很多手机上的图片处理软件都能实现。

PIL是一个功能非常强大的Python图像处理标准库,但是呢,由于PIL支持Python2.7,所以使用Python3的程序猿们又在PIL的基础上分离出来了一个分支,创建了另外一个库Pillow,是可以支持Python3。Pillow兼容了PIL的大部分语法,使用起来也非常的简单。

对应代码如下:


 

# -*- 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('./result/python'+str(index) + '.png', 'PNG')
        index += 1



if __name__ == '__main__':
    file_path = "1.jpg"
    image = Image.open(file_path)
    #image.show()
    image = fill_image(image)
    image_list = cut_image(image)
    save_images(image_list)

github地址:

https://github.com/yangxuan0928/cut_image

在本地使用git clone命令将源码下载下来,然后将要分解的图片放在项目目录里面。

依赖

Python 2.7

PIL: pip install pillow

Python 3

PIL: pip3 install pillow

修改代码中:

file_path = "你的照片名字.照片后缀"

然后运行,然后到result目录中去找生成的照片。

拼图前:

拼图后:


代码非原创,我只是代码的搬运工。

猜你喜欢

转载自blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/81742341