python 批量修改图片大小

  1. 引用的模块
from PIL import Image
  1. 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
  1. 引用
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

第一个参数为图片的目录路径,第二个参数是(目录路劲的回掉方法),第三个参数是图片处理回掉方法

源代码参考:
https://github.com/lidc-lee/Python_Tool/blob/master/reSizeOfPic.py

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值