使用python如何实现一个切割图片功能

  介绍

使用python如何实现一个切割图片功能吗?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

这个小程序可以自己设定行数和列数进行图片切割

导入操作系统
  从公益诉讼导入图像
  
  def splitimage (rownum src colnum dstpath):
  img=Image.open (src)
  w h=img.size
  如果rownum & lt;=h和colnum & lt;=w:
  打印(& # 39;原始图像信息:% sx % s, % s, % & # 39;% (w h, img。格式,img.mode))
  打印(& # 39;开始处理图片切割,请稍候…& # 39;)
  
  s=os.path.split (src)
  如果dstpath==& # 39; & # 39;:
  dstpath=s [0]
  fn=s [1] .split(& # 39; # 39;公司)
  basename=fn [0]
  ext=fn [1]
  
  num=0
  rowheight=h//rownum
  colwidth=w//colnum
  r的范围(rownum):
  c的范围(colnum):
  盒=(c * colwidth, r * rowheight (c + 1) * colwidth, (r + 1) * rowheight)
  img.crop .save (os.path(盒)。加入(dstpath basename + & # 39; _ # 39;+ str (num) + & # 39;强生# 39;+ ext), ext)
  num=num + 1
  
  打印(& # 39;图片切割完毕,共生成% s张小图片强生# 39;% num)
  其他:
  打印(& # 39;不合法的行列切割参数! & # 39;)
  
  src=https://www.yisu.com/zixun/input(“请输入图片文件路径:')
  如果os.path.isfile (src):
  dstpath=输入(“请输入图片输出目录(不输入路径则表示使用源图片所在目录):')
  如果(dstpath==?或os.path.exists (dstpath):
  行=int(输入(“请输入切割行数:"))
  坳=int(输入(“请输入切割列数:"))
  如果行> 0和坳> 0:
  splitimage (src、行坳dstpath)
  其他:
  打印(“无效的行列切割参数!”)
  其他:
  打印(“图片输出目录% s不存在!”% dstpath)
  其他:
  打印(“图片文件% s不存在!”% src) 

运行效果

使用python如何实现一个切割图片功能

使用python如何实现一个切割图片功能

使用python如何实现一个切割图片功能