这篇文字讲述如何使用Python把一张完整的大图切割成9份小图片,制作朋友圈九宫格图文分享。
原图如下:
我们想要利用这张图制作高逼格的九宫格朋友圈分享。
达到类似于这样的效果:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gtn8DITU-1588081268709)(https://upload-images.jianshu.io/upload_images/22699699-57ef2ecc5e543252.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]
实现原理非常简单,那就是利用PIL库对原图不断画小区域然后切下来存储成新的小图片。
假设每一个格子的宽和高分别是w、h,那么第row行(从0开始计数),第col列(从0开始计数)的格子左上角座标和右下角座标分别是(col * w, row * h),(col * w + w, r * h + h)。
在学习过程中有什么不懂得可以加我的
python学习qun,855408893
群里有不错的学习视频教程、开发工具与电子书籍。
与你分享python企业当下人才需求及怎么从零基础学习好python,和学习什么内容
code snippet:
#! /usr/local/bin/python3
# -*- coding: utf-8 -*-
fromPILimportImage
defcut_image(image):
width, height = image.size
item_width = width /3.0
item_height = height /3.0
box_list = []
forrowinrange(0,3):
forcolinrange(0,3):
box = (col * item_width, row * item_height,( col +1) * item_width,( row +1) * item_height)
box_list.append( box )
image_list = [image.crop(box)forboxinbox_list]
returnimage_list
defsave_images(image_list):
dirName ='output'
ifFalse== os.path.exists( dirName ):
os.makedirs( dirName )
index =1
forimageinimage_list:
image.save('./output/python'+str(index) +'.png','PNG')
index +=1
if__name__ =='__main__':
image = Image.open("use.png")
image_list = cut_image(image)
save_images(image_list)
为了能在朋友圈中预览时看到所有图片的完整样子,建议保证自己的原始图片是正方形的,然后再运行这个脚本,在output中得到九张图片。最后,嗯,就可以去秀了!