新闻动态

python 批量压缩图片的脚本

发布日期:2022-03-26 16:42 | 文章来源:脚本之家

简介

用Python批量压缩图片,把文件夹或图片直接拖入即可

需要 Needs

Python 3

Pillow (用pip install pillow来安装即可)

用法 Usage

把文件夹或图片直接拖入即可。如果拖入的是文件夹,则会遍历子文件夹把所有图片都压缩了。

注意,压缩后的文件会直接替换原来的文件,文件名不变,尺寸不变,只改变压缩质量。

文件的开头有两个变量:

SIZE_CUT = 4 表示大于4MB的图片都会进行压缩

QUALITY = 90 表示压缩质量90,这个质量基本人眼是看不出来啥差距的,而且很多原先10M的图能压缩一半。80以下的质量大概就不太行了。

代码

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# Created by Mario Chen, 01.04.2021, Shenzhen
# My Github site: https://github.com/Mario-Hero
import sys
import os
from PIL import Image
SIZE_CUT = 4# picture over this size should be compressed. Units: MB
QUALITY = 90  # 90 is good, this number should not be smaller than 80.

def isPic(name):
 namelower = name.lower()
 return namelower.endswith("jpeg") or namelower.endswith("jpg") or namelower.endswith("png")

def compressImg(file):
 #print("The size of", file, "is: ", os.path.getsize(file))
 im = Image.open(file)
 im.save(file, quality=QUALITY)

def compress(folder):
 try:
  if os.path.isdir(folder):
print(folder)
file_list = os.listdir(folder)
for file in file_list:
 if os.path.isdir(folder+"/"+file):
  #print(folder +"/"+ file)
  compress(folder +"/"+file)
 else:
  if isPic(file):if os.path.getsize(folder + "/" + file) > (SIZE_CUT * 1024 * 1024):
compressImg(folder + "/" + file)
print(file)
  else:
if isPic(folder):
 if os.path.getsize(folder) > (SIZE_CUT * 1024 * 1024):
  compressImg(folder)
 except BaseException:
  return

if __name__ == '__main__':
 for folder in sys.argv:
  #print(folder)
  compress(folder)
 print("Finish.")
 #os.system("pause")

实现效果

压缩后大小

另外一种图片压缩实现方式

同样自动遍历目录下的图片

import os
from PIL import Image
import threading,time
def imgToProgressive(path):
 if not path.split('.')[-1:][0] in ['png','jpg','jpeg']:  #if path isn't a image file,return
  return
 if os.path.isdir(path):
  return
##########transform img to progressive
 img = Image.open(path)
 destination = path.split('.')[:-1][0]+'_destination.'+path.split('.')[-1:][0]
 try:
  print(path.split('\\')[-1:][0],'开始转换图片')
  img.save(destination, "JPEG", quality=80, optimize=True, progressive=True) #转换就是直接另存为
  print(path.split('\\')[-1:][0],'转换完毕')
 except IOError:
  PIL.ImageFile.MAXBLOCK = img.size[0] * img.size[1]
  img.save(destination, "JPEG", quality=80, optimize=True, progressive=True)
  print(path.split('\\')[-1:][0],'转换完毕')
 print('开始重命名文件')
 os.remove(path)
 os.rename(destination,path)
for d,_,fl in os.walk(os.getcwd()): #遍历目录下所有文件
 for f in fl:
  try:
imgToProgressive(d+'\\'+f)
  except:
pass

以上就是python 批量压缩图片的脚本的详细内容,更多关于python 批量压缩图片的资料请关注本站其它相关文章!

海外服务器租用

版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。

相关文章

实时开通

自选配置、实时开通

免备案

全球线路精选!

全天候客户服务

7x24全年不间断在线

专属顾问服务

1对1客户咨询顾问

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部