python批量修改图片大小的方法

yipeiwu_com5年前Python基础

本文实例为大家分享了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设计】。

相关文章

Pytorch 实现计算分类器准确率(总分类及子分类)

分类器平均准确率计算: correct = torch.zeros(1).squeeze().cuda() total = torch.zeros(1).squeeze().cuda...

pandas实现将dataframe满足某一条件的值选出

在读取数据的时候发现,想把数据中第六列含问号的数据挑出来 import pandas as pd data = pd.read_table('breast-cancer-wisc...

Python中的__slots__示例详解

前言 相信Python老鸟都应该看过那篇非常有吸引力的Saving 9 GB of RAM with Python's slots 文章,作者使用了__slots__让内存占用从25.5...

跟老齐学Python之玩转字符串(2)

上一章中已经讲到连接两个字符串的一种方法。复习一下: >>> a= 'py' >>> b= 'thon' >>> a+b 'py...

Python中的函数式编程:不可变的数据结构

让我们首先考虑正方形和长方形。如果我们认为在接口方面,忽略了实现细节,方块是否是矩形的子类型? 子类型的定义取决于Liskov代换原理。为了成为一个子类型,它必须能够完成超级类型所做的一...