将软件复制到需要压缩图片的文件夹,双击软件,就会遍历当前文件夹,将所有jpg格式的文件压缩,png文件的话,会转换成jpg文件。

python代码:

#coding:utf-8
'''
  python图片处理
'''
import PIL.Image as image
import os
import io
 
#等比例压缩图片
def resizeImg(**args):
  args_key = {'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':100}
  arg = {}
  for key in args_key:
    if key in args:
      arg[key] = args[key]
  im = image.open(arg['ori_img'])
  ori_w,ori_h = im.size
  widthRatio = heightRatio = None
  ratio = 1
  if (ori_w and ori_w > arg['dst_w']) or (ori_h and ori_h > arg['dst_h']):
    if arg['dst_w'] and ori_w > arg['dst_w']:
      widthRatio = float(arg['dst_w']) / ori_w #正确获取小数的方式
    if arg['dst_h'] and ori_h > arg['dst_h']:
      heightRatio = float(arg['dst_h']) / ori_h
    if widthRatio and heightRatio:
      if widthRatio < heightRatio:
        ratio = widthRatio
      else:
        ratio = heightRatio
    if widthRatio and not heightRatio:
      ratio = widthRatio
    if heightRatio and not widthRatio:
      ratio = heightRatio
    newWidth = int(ori_w * ratio)
    newHeight = int(ori_h * ratio)
  else:
    newWidth = ori_w
    newHeight = ori_h
  im.resize((newWidth,newHeight),image.ANTIALIAS).save(arg['dst_img'],quality=arg['save_q'])
 
def list_all_files(rootdir):
    import os
    _files = []
    list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
    for i in range(0,len(list)):
           path = os.path.join(rootdir,list[i])
           if os.path.isdir(path):
              _files.extend(list_all_files(path))
           if os.path.isfile(path):
              _files.append(path)
    return _files
 
_fs = list_all_files('.')
#将第一阶段的文件遍历出来
for f in _fs:
  if f.endswith('.jpg') or f.endswith('.png'):
    if f.endswith('.png'):
        img = image.open(f)
        img =  img.convert('RGB')
        f = f.replace(".png",".jpg")
        img.save(f)
        #源图片
    ori_img = f
        #目标图片
    dst_img = f
        #目标图片大小
    dst_w = 1980
    dst_h = 1080
        #保存的图片质量
    save_q = 75
    resizeImg(ori_img=ori_img,dst_img=dst_img,dst_w=dst_w,dst_h=dst_h,save_q=save_q)
    print(f)

本来是自己需要才写的工具,目的很简单,就是压缩图片,至于备份什么的,都不是我的需求,所以没考虑很多,确实如果分享给其他人使用,有很多不方便的地方,有很多考虑不周,感谢各位的建议。
不过我不打算做修改了,其实代码也是网上东拼西凑出来的,我也没有版权之类的,哪位同学想拿去修改,就拿去吧!

最后修改:2023 年 09 月 26 日
如果觉得我的文章对你有用,请随意赞赏