Python实现微信朋友圈九宫格图片分割

何川
何川
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍如何利用Python的Pillow库实现图片分割功能。通过读取图像,将其填充为正方形后均分为9张小图,完美适配微信朋友圈最多9张图的发布限制。代码包含填充、裁剪及保存逻辑,适合Python初学者参考学习。

Python实现微信朋友圈九宫格图片分割

程序实现思路:

本次开发主要依赖PIL(Python Image Library)库进行图像数据处理。

PIL是Python中功能强大的图像处理标准库,但仅支持Python 2.7。鉴于当前多数开发者使用Python 3.x,PIL衍生出Pillow库以兼容Python 3环境。在运行本程序前,请确保已安装Pillow库。

程序首先读取待分割的图像至变量,随后定义fill_image()方法。该方法的作用是将尺寸不一的原图填充为长宽相等的正方形图像,以便后续统一处理。

经fill_image()处理后得到正方形图像,接着利用cut_image()方法将其分割为9张子图。此举旨在适配微信朋友圈最多允许发布9张图片的限制。


from PIL import Image
import sys
#先将 input image 填充为正方形
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:#原图宽大于高,则填充图片的竖直维度 #(x,y)二元组表示粘贴上图相对下图的起始位置,是个坐标点。
    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
  item_width = int(width / 3) #因为朋友圈一行放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(str(index) + '.png', 'PNG')
    index += 1
if __name__ == '__main__':
  file_path = "2.jpg" #图片保存的地址
  image = Image.open(file_path)
  #image.show()
  image_new = fill_image(image)
  image_list = cut_image(image_new)
  save_images(image_list)

若需深入了解Pillow库的具体用法,可查阅相关文档。

以上内容为本文全部介绍,希望能对读者的学习有所帮助,欢迎继续支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表