大家应该经常看到有人在朋友圈发九宫格图吧。本质就是把一张图片剪成九份,然后把九张图片一起发到微信里。说到图片裁剪,Python可以实现。使用的主要Python库是Pillow,可以使用pipinstallpillow安装。图像切割的主要步骤如下:打开待处理图像,判断打开的图像是否为正方形。如果是正方形,就进行九等分,如果不是正方形,先用白色填充形成一个正方形,然后进行九等分,保存处理后的图像。主要实现代码如下:#填充新图像deffill_image(image):width,height=image.size_length=widthifheight>width:_length=heightnew_image=Image.new(image.mode,(_length,_length),color='white')如果宽度>高度:new_image.paste(image,(0,int((_length-height)/2)))else:new_image.paste(image,(int((_length-width)/2),0))returnnew_image#cropimagedefcut_image(image):width,height=image.size_width=int(width/3)box_list=[]foriinrange(0,3):forjinrange复制代码(0,3):box=(j*_width,i*_width,(j+1)*_width,(i+1)*_width)box_list.append(box)image_list=[image.crop(box)框inbox_list]returnimage_list#保存图片到图片列表defsave_images(image_list,res_dir):index=1如果不是os.path.exists(res_dir):os.mkdir(res_dir)forimage_list:new_name=os.path.join(res_dir,str(index)+'.png')image.save(new_name,'PNG')index+=1原图:效果图:源码公众号后台回复200901获取欢迎微信搜索Python小二,第一时间阅读获取源码,回复关键词1024即可领取各种编程自己整理的语言免费学习资料。
