Python批量修改图片大小的实现方法

巷口听风
巷口听风
发布时间:2026-10-13 | 6人浏览过
原创

本文介绍了如何使用Python的PIL库批量修改图片大小。通过定义resize_image函数处理单张图片,并结合BFS_Dir函数遍历文件夹,实现了对目录下所有图片的自动缩放处理。文章提供了完整的源代码参考,包括路径处理、尺寸计算及文件保存逻辑,适合需要批量调整图像分辨率的开发者参考。

本文分享了一段使用Python批量调整图片尺寸的具体代码示例,供读者参考学习。

所需引用的模块

from PIL import Image

关于Image模块的使用说明

def resize_image(img_path):
  try:
    mPath, ext = os.path.splitext(img_path)
    if astrcmp(ext, ".png") or astrcmp(ext, ".jpg"):
      img = Image.open(img_path)
      (width, height) = img.size

      if width != new_width:
        new_height = int(height * new_width / width)
        out = img.resize((new_width, new_height), Image.ANTIALIAS)
        new_file_name = '%s%s' % (mPath, ext)
        out.save(new_file_name, quality=100)
        Py_Log("图片尺寸修改为:" + str(new_width))
      else:
        Py_Log("图片尺寸正确,未修改")
    else:
      Py_Log("非图片格式")
  except Exception, e:
    print e

def printFile(dirPath):
  print "file: " + dirPath
  resize_image(dirPath)
  return True

代码引用部分

if __name__ == '__main__':
  path = "E:\pp\icon_setting.png"
  new_width = 50
  try:
    b = printFile(path)
    Py_Log("\r\n     **********\r\n" + "*********图片处理完毕*********" + "\r\n     **********\r\n")
  except:
    print "Unexpected error:", sys.exc_info()

上述示例仅针对单一图片进行修改。若需对文件夹内的所有图片进行批量处理,则需引入循环机制。在原有基础上增加遍历逻辑,例如:

def BFS_Dir(dirPath, dirCallback=None, fileCallback=None):
  queue = []
  ret = []
  queue.append(dirPath);
  while len(queue) > 0:
    tmp = queue.pop(0)
    if os.path.isdir(tmp):
      ret.append(tmp)
      for item in os.listdir(tmp):
        queue.append(os.path.join(tmp, item))
      if dirCallback:
        dirCallback(tmp)
    elif os.path.isfile(tmp):
      ret.append(tmp)
      if fileCallback:
        fileCallback(tmp)
  return ret

该函数第一个参数指定图片所在的目录路径,第二个参数为处理目录时的回调方法,第三个参数则是处理具体图片文件的回调方法。

完整源代码可参考:Python_Tool

以上就是本文的全部内容,希望能为各位的学习提供一定帮助,同时也欢迎大家继续支持本站。

本站声明

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

Python 相关产品和应用

全部下载

专题列表