文章目录

  • 一、项目需求
  • 二、python实现代码
  • 三、实现效果
  • 四、参考文献

一、项目需求

图片太大,导致word文档占用太多内存卡死,需要通过压缩来减小文件的体积。

二、python实现代码

以下代码用于批量压缩png/jpg格式的图片文件,遇到报错就使用pip大法安装一下对应的类库就可以了。

dynamic_quality.py

import PIL.Image
from math import log
from SSIM_PIL import compare_ssimdef get_ssim_at_quality(photo, quality):"""Return the ssim for this JPEG image saved at the specified quality"""ssim_photo = "tmp.jpg"# optimize is omitted here as it doesn't affect# quality but requires additional memory and cpuphoto.save(ssim_photo, format="JPEG", quality=quality, progressive=True)ssim_score = compare_ssim(photo, PIL.Image.open(ssim_photo))return ssim_scoredef _ssim_iteration_count(lo, hi):"""Return the depth of the binary search tree for this range"""if lo >= hi:return 0else:return int(log(hi - lo, 2)) + 1def jpeg_dynamic_quality(original_photo):"""Return an integer representing the quality that this JPEG image should besaved at to attain the quality threshold specified for this photo class.Args:original_photo - a prepared PIL JPEG image (only JPEG is supported)"""ssim_goal = 0.9 #the original value is 0.95hi = 35 #the original value is 85lo = 30 #the original value is 80# working on a smaller size image doesn't give worse results but is faster# changing this value requires updating the calculated thresholdsphoto = original_photo.resize((200, 200))# if not _should_use_dynamic_quality():#     default_ssim = get_ssim_at_quality(photo, hi)#     return hi, default_ssim# 95 is the highest useful value for JPEG. Higher values cause different behavior# Used to establish the image's intrinsic ssim without encoder artifactsnormalized_ssim = get_ssim_at_quality(photo, 10)selected_quality = selected_ssim = None# loop bisection. ssim function increases monotonically so this will convergefor i in range(_ssim_iteration_count(lo, hi)):curr_quality = (lo + hi) // 2curr_ssim = get_ssim_at_quality(photo, curr_quality)ssim_ratio = curr_ssim / normalized_ssimif ssim_ratio >= ssim_goal:# continue to check whether a lower quality level also exceeds the goalselected_quality = curr_qualityselected_ssim = curr_ssimhi = curr_qualityelse:lo = curr_qualityif selected_quality:return selected_quality, selected_ssimelse:default_ssim = get_ssim_at_quality(photo, hi)return hi, default_ssim

cpressJPG.py

from PIL import Image
import dynamic_quality
def compress(filename,originpath,targetpath):name = filename.rstrip('.png').rstrip('.jpg')im = Image.open(originpath+filename)# print(im.format,im.size,im.mode)im = im.convert('RGB')im.format = "JPEG"new_photo = im.copy()new_photo.thumbnail(im.size,resample=Image.ANTIALIAS)save_args = {'format':im.format}# print(save_args)# if im.format=='JPEG':# save_args['quality']=20save_args['quality'],value=dynamic_quality.jpeg_dynamic_quality(im)save_args['optimize']=Truesave_args['progressive=True']=True# print("JPEG Quality Changed")# elif im.format=='PNG':#     save_args['format']='JPEG'#     save_args['quality']=5#     print("PNG Quality Changed")new_photo.save(targetpath+name+".jpg",**save_args)if __name__ == '__main__':import osoriginpath = "./images/png/"targetpath = "./images/test/"for root, dirs, files in os.walk(originpath):for file in files:compress(file,originpath,targetpath)

三、实现效果

压缩之前1176KB:

压缩之后54KB:

最终的图片结果是差不多的:

再细致一点,我们比较jpg压缩前后的大小如下,可以得出以下结论:
从png格式转换到jpg格式,大小压缩了10倍;
降低jpg格式前后,大小压缩了3倍;

四、参考文献

1.使用python对图片进行批量压缩 https://zhuanlan.zhihu.com/p/161274600

使用python批量压缩图片文件相关推荐

  1. 使用Python批量压缩图片

    使用Python批量压缩图片 Python脚本 #coding:utf-8 import Image import os import os.path def picIsCorrect(fileSuf ...

  2. Python批量压缩图片

    Python批量压缩图片 代码如下 代码如下 可支持压缩指定单张图片,单个文件夹,多个文件夹,可根据自己实际场景的需求扩展丰富.话不多说,上代码. # @Time : 2021/10/14 9:16i ...

  3. 如何使用python批量压缩图片_python利用Guetzli批量压缩图片

    Google 又开源了,这次开源了一款图像算法工具 Guetzli.Guetzli,在瑞士德语中是"cookie(曲奇)"的意思,是一个针对数码图像和网页图像的 JPEG 编码器, ...

  4. python批量压缩图片_Python图片批量压缩到指定大小并将JPG转为PNG格式

    背景: 待压缩的图片大小有几十KB到近10M大小不等,且绝大部分图片为JPG格式.这些待压缩图片放在picture文件夹下 以及picture文件夹下的子文件夹中 现需要将picture文件夹下这些图 ...

  5. 如何使用python批量压缩图片_利用Python 批量压缩图片

    方法一 直接调整宽高 先放参考资料:如何用Python智能批量压缩图片? import math from glob import glob from PIL import Image import ...

  6. 宝塔数据盘满了,怎么办?linux批量压缩图片文件,2步完成压缩

    问题: 问题分析: 登录服务器,先看下文件大小,哪些占用比较大.(演示系统为 centos 7.9) du -h --max-depth=1 #查找当前目录下文件大小 效果如下, 然后逐级查看,直到确 ...

  7. Python批量压缩图片大小并保存到相应的新文件夹,不覆盖源文件

    网上下载的小姐姐套图合集因为原图非常大,一张图十几或者几十M,一套图下来总共可能上百G,所以需要批量压缩处理一下,虽然PS也可以办到,但是代码更灵活,写个Python程序处理了一下,讲每张图长宽缩为2 ...

  8. 如何使用python批量压缩图片_python 实现图片批量压缩的示例

    项目中大量用到图片加载,由于图片太大,加载速度很慢,因此需要对文件进行统一压缩 一:导入包 from PIL import Image import os 二:获取图片文件的大小 def get_si ...

  9. 如何使用python批量压缩图片_Python实现批量压缩图片

    # -*- coding: utf-8 -*- """ __author__= 'Du' __creation_time__= '2018/1/5 10:06' &quo ...

  10. 如何使用python批量压缩图片_使用python脚本批量压缩图片大小

    需要安装第三方模块PIL#coding:utf-8 import Image import os #图片压缩批处理 def compressImage(srcPath,dstPath): for fi ...

最新文章

  1. Android Studio 受不了了
  2. CentOS 7.6 MySQL 8.0 RPM包方式安装及新特性介绍
  3. TP5.1类的自动加载
  4. 自动完成--autoComplete插件(2)
  5. LeetCode刷题: 整数反转
  6. qt如何捕获应用程序输出_企业应用程序中需要捕获的5大Java性能指标
  7. liunx 命令手册 (chm)
  8. Linux中7个判断文件系统类型的方法
  9. catia创成式外形设计如何将两个面相合_汽车研发:车门铰链设计及布置要求解析!...
  10. HDU 4946 Area of Mushroom 凸包 第八次多校
  11. GIS应用开发AO(1)_普通几何图形绘制
  12. 初学JAVA,开发环境的搭建(JDK和Eclipse的安装)
  13. 分享一个好看的邮件html模板
  14. 通过第三方平台超级鹰进行登录页面验证码识别
  15. 12/14 计算器雏形
  16. 如何使用PDF Expert将文本添加到PDF?
  17. 计算机亮度快捷键,电脑亮度怎么调(一个快捷键就可以设置亮度了)
  18. 如何用C语言画立体几何图形,立体几何图形公式大全
  19. 事务四大特征:原子性,一致性,隔离性和持久性(ACID)
  20. H5页面input输入框,在ios手机中被顶出页面解决方案

热门文章

  1. 使用cache tier
  2. 0723Python总结-递归函数及练习
  3. EasyUI——基本布局
  4. 苹果手机怎么在iTunes备份
  5. 论文参考文献正确插入方法 (一)
  6. Excel密码保护怎么解密码
  7. 【常用表】常用泰勒公式与常用等价
  8. fid和is_【深度学习】生成式对抗网络(GAN)的常见评价指标:IS/FID/JS散度
  9. 欲为苍鹰,勿与鸟鸣, 欲为强者,莫与弱争!
  10. Spring5开发新功能