Python批量改变图片的size

因为老师的要求,要把JPG文件夹下的凡是等于128128的图片都保留原状,其他size的图片则resize成256256的大小。所以就写了一个脚本,效率不高,但是能够完成任务就过去了。
本来的文件目录结构是:

《Python批量改变图片的size》 图片.png

import os
from PIL import Image
import sys

#获取path目录下的所有文件
def get_imlist(path):
    return[os.path.join(path,f) for f in os.listdir(path)]

def change_size(path):
    directorys=get_imlist(path)
    for directory in directorys:
                #不是图片文件就跳过
        if not(directory.endswith('j.jpg') or directory.endswith('p.png') or directory.endswith('b.bmp')):
            pass
        else:
            img=Image.open(directory)
            s="/"
                    #获取文件名(含后缀)
            oimage_name=directory[directory.rfind(s)+1:]
             #获取原图的宽度和高度
            (oimage_width,oimage_height)=img.size
            if oimage_width==128 and oimage_height==128:
                to_save=path+'/128*128/'+oimage_name
                img.save(to_save)
               #移除原图
                os.remove(directory)
            else:
                to_save=path+'/256*256/'+oimage_name
                new_width=256
                new_height=256
                out=img.resize((new_width,new_height),Image.ANTIALIAS)
                out.save(to_save)
                os.remove(directory)

change_size("/home/winney/image_db/jpg")
change_size("/home/winney/image_db/bmp")
change_size("/home/winney/image_db/png")
    原文作者:exmexm
    原文地址: https://www.jianshu.com/p/a1c767a8e581
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞