前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何发朋友圈九宫格图片

如何发朋友圈九宫格图片

作者头像
苏生不惑
发布2019-08-17 13:27:40
8940
发布2019-08-17 13:27:40
举报
文章被收录于专栏:苏生不惑苏生不惑

朋友圈和微博的图片都是九宫格,如何让一张图切为9图呢,在github上找到 https://github.com/yumendy/nine_picture[1] 这个项目。

安装pil

pip install pillow

源码

代码语言:javascript
复制
from PIL import Imageimport sys

class NinePictures(object):    def __init__(self, file_path, mode):        self.image = Image.open(file_path)        self.width, self.height = self.image.size        if mode == 'C':            self.length = self.width if self.width < self.height else self.height            self.cut_image()        elif mode == 'F':            self.length = self.width if self.width > self.height else self.height            self.fill_image()
    def cut_image(self):        if self.width < self.height:            self.cut_height()        elif self.width > self.height:            self.cut_width()
    def cut_height(self):        box = (0, (self.height - self.width) / 2, self.width, (self.height + self.width) / 2)        self.image = self.image.crop(box)
    def cut_width(self):        box = ((self.width - self.height) / 2, 0, (self.height + self.width) / 2, self.height)        self.image = self.image.crop(box)
    def fill_image(self):        new_image = Image.new(self.image.mode, (self.length, self.length), color='white')        if self.width > self.height:            self.fill_height(new_image)        elif self.width < self.height:            self.fill_width(new_image)
    def fill_height(self, new_image):        new_image.paste(self.image, (0, (self.length - self.height) / 2))        self.image = new_image
    def fill_width(self, new_image):        new_image.paste(self.image, ((self.length - self.width) / 2, 0))        self.image = new_image
    def process(self):        length = self.length / 3        left_list = [0, length, length * 2] * 3        upper_list = [0] * 3 + [length] * 3 + [length * 2] * 3        right_list = [length, length * 2, length * 3] * 3        lower_list = [length] * 3 + [length * 2] * 3 + [length * 3] * 3
        box_list = zip(left_list, upper_list, right_list, lower_list)
        image_list = [self.image.crop(box) for box in box_list]
        return image_list
    def save_image(self):        image_list = self.process()
        order_number = 1        for image in image_list:            image.save(str(order_number) + '.png', 'PNG')            order_number += 1

if __name__ == '__main__':    image_mode = sys.argv[1]    image_path = sys.argv[2]    app = NinePictures(image_path, image_mode)    app.save_image()

使用

代码语言:javascript
复制
python main.py C image_path # 居中裁剪
python main.py F image_path # 白色填充

以我的公众号图片为例 python main.py C qr.jpg

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 苏生不惑 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装pil
  • 源码
  • 使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档