powershell + python 批量更改图片大小

来源:互联网 发布:pcb开料软件 编辑:程序博客网 时间:2024/06/06 06:51

python也可以用来搜索到图片,但用powershell更方便简单

powershell图片搜索代码:

Get-ChildItem -Path G:\ -Recurse| Where-Object {$_.name -like '*.jpg' -and $_.length -gt 2Mb} | ForEach-Object {$_.fullname} >> d:\path.txt

看一行就搞定了,解释一下,上面是搜索G盘中大于2M的jpg格式的图片(想搜其他的自己改啊),然后将完整路径保存至d盘path.txt档案中

下面用Python来更改图片的大小

代码如下:

# -*- conding: utf-8 -*-

import os
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES =True
imagepath = open(r"d:\path.txt") #从文件读取图片路径
lines = imagepath.readlines() #读取全部
for line in lines: #按行读取
    line = line.strip('\n')
    print(line)
    img = Image.open(line)
    new_size = tuple( [size//2 for size in img.size] ) # 高度、宽度为原有的一半
    print("resize OK")
    new_img = img.resize(new_size)
    try:
       
    #new_name = os.path.join(pic_dir,"small_"+filename) #更名
        new_img.save(line)
        print("OK")
    except:
        print("error")
        continue


注:python版本为3 ,部分中文名字的图片无法有效识别,正在开启的图片无法更改会出错,所以后面做了个简单排错。




0 0