使用Python快速压缩目录中图片
使用Python快速压缩目录中图片
脚本语言
#coding:utf-8
import Image
import os
import logging
import sqlite3
from PIL import ImageFileImageFile.LOAD_TRUNCATED_IMAGES = True#全局变量 数据库链接
global cx #全局变量 数据库链接游标
global cu#全局变量 创建表单标识
global createTableFlag ##########################################
# @function 判断是否为图片
# @param srcFile 待压缩图片
##########################################
def picIsCorrect(fileSuffix):if fileSuffix == ".png" or fileSuffix == ".jpg" or fileSuffix == ".jpeg":return Trueelse:return False##########################################
# @function 判断图片大小是否需要压缩
# @param srcFile 待压缩图片
##########################################
def picIsBig(srcFile):size = os.path.getsize(srcFile)/1024if size > 0 :return Trueelse:return False##########################################
# @function 判断图片大小是否被压缩过
# @description 如果图片信息存在于数据库中,则表明图片被压缩过,不需要再次压缩
# @param basename 待压缩图片名称
##########################################
def picIsCompressed(basename , dstFile):if selectTableCompressLog(basename , dstFile):#print(" images is already compressed which named " + basename + ' or path equals ' + dstFile)return Trueelse:return False ##########################################
# @function 创建记录压缩信息的表单
# @description 如果图片信息存在于数据库中,则表明图片被压缩过,不需要再次压缩
##########################################
def createTableCompressLog():#全局变量 创建表单标识global createTableFlag if createTableFlag :try:create_tb_cmd='''create table if not exists compresslog (id varchar(64) primary key , name varchar(64) UNIQUE , path varchar(1024) UNIQUE , size integer , org_size integer , status integer)'''#主要就是上面的语句cu.execute(create_tb_cmd) createTableFlag = Falseexcept:logging.info(" table compresslog maybe exist , create table compresslog fail ")createTableFlag = False##########################################
# @function 查询表单中图片信息是否存在
# @description 如果图片信息存在于数据库中,则表明图片被压缩过,不需要再次压缩
##########################################
def selectTableCompressLog(basename , dstFile):#进行建表语句createTableCompressLog()#打开游标cu.execute("select * from compresslog where id = '" + basename + "'" + " or path = '" + dstFile + "'")#执行查询操作rows = cu.fetchall()if len(rows) > 0:print(" images is already compressed which named " + basename + ' or path equals ' + dstFile)return Trueelse:print(" images is not compressed which named " + basename + ' or path equals ' + dstFile)return False ##########################################
# @function 向压缩信息表单插入记录
# @description 如果图片信息存在于数据库中,则表明图片被压缩过,不需要再次压缩
##########################################
def insertTableCompressLog(basename , filename , dstFile , dsize , osize):#进行建表语句createTableCompressLog()#没有数据则插入数据if not selectTableCompressLog(basename , dstFile):#插入数据:cu.execute("insert into compresslog values('" + basename + "', '" + filename + "' , '" + dstFile + "' , " + str(dsize) + " , " + str(osize) + " , 0)") #提交数据cu.commit() ##########################################
# @function 图片压缩操作
# @param srcFile 待压缩图片
##########################################
def compressImage(srcPath,dstPath): for filename in os.listdir(srcPath): #如果不存在目的目录则创建一个,保持层级结构if not os.path.exists(dstPath):os.makedirs(dstPath) #拼接完整的文件或文件夹路径srcFile=os.path.join(srcPath,filename)dstFile=os.path.join(dstPath,filename)srcFiledirName = os.path.dirname(srcFile)basename = os.path.basename(srcFile) #获得文件全称 例如 migo.pngfilename, fileSuffix = os.path.splitext(basename) #获得文件名称和后缀名 例如 migo 和 png #如果是文件就处理if os.path.isfile(srcFile) and picIsCorrect(fileSuffix) and picIsBig(srcFile) and (not picIsCompressed(basename , dstFile)): #打开原图片缩小后保存,可以用if srcFile.endswith(".jpg")或者split,splitext等函数等针对特定文件压缩sImg=Image.open(srcFile).convert('RGB') #获取原图片长宽w,h=sImg.size #获取压缩前图片大小,单位KBosize = os.path.getsize(srcFile)/1024if osize > 4096 :width = w/(compressRatio + 0.25)height = h/(compressRatio + 0.25)dImg=sImg.resize((int(width),int(height)),Image.ANTIALIAS)elif osize > 2048 :width = w/(compressRatio + 0.2)height = h/(compressRatio + 0.2)dImg=sImg.resize((int(width),int(height)),Image.ANTIALIAS)elif osize > 1024 :width = w/(compressRatio + 0.1)height = h/(compressRatio + 0.1)dImg=sImg.resize((int(width),int(height)),Image.ANTIALIAS)else:width = w/(compressRatio + 0.05)height = h/(compressRatio + 0.05)dImg=sImg.resize((int(w/width),int(h/height)),Image.ANTIALIAS) #保存压缩后文件,单位KB dImg.save(dstFile) #获取压缩后文件大小dsize = os.path.getsize(dstFile)/1024#如果压缩后,压缩图片大于原图片,则在用原图片覆盖被压缩的图片if(dsize > osize):sImg.save(dstFile)dsize = os.path.getsize(dstFile)/1024#插入数据,被压缩的图片信息记录到数据库中,下次不再压缩insertTableCompressLog(basename , filename , dstFile , dsize , osize)logging.info("srcFile: " + srcFile + " dstFile: " + dstFile)logging.info("filename: " + filename + " fileSuffix: " + fileSuffix)logging.info("originally size:" + str(osize))logging.info("compressed size:" + str(dsize) + " " + dstFile + " compressed succeeded" )print("srcFile: " + srcFile + " dstFile: " + dstFile + "filename: " + filename + " fileSuffix: " + fileSuffix + "originally size:" + str(osize) + "compressed size:" + str(dsize) + " " + dstFile + " compressed succeeded" )#如果是文件夹就递归if os.path.isdir(srcFile):compressImage(srcFile,dstFile)##########################################
# @function 主函数执行区域
# @description 快速压缩图片
##########################################
if __name__=='__main__': #压缩比率compressRatio = 1.1#是否建表标识createTableFlag = True#Create Connection to INSERT COMPRESS IMAGES INFO TO DATABASEcx = sqlite3.connect("./database.db")#获取游标cu = cx.cursor() #设置打印日志格式logging.basicConfig(filename='compress.log', level=logging.INFO)#进行递归压缩compressImage('/path/need compress dir/', '/path/save compress dir/')
将上述文本保存为compress.py,修改上述文件中,需要压缩的目录,和需要存放被压缩的目录
执行命令
chmod +x compress.py
python ./compress.py
说明事项
(1) 修改低于多少KB的文件不被压缩
##########################################
# @function 判断图片大小是否需要压缩
# @param srcFile 待压缩图片
##########################################
def picIsBig(srcFile):size = os.path.getsize(srcFile)/1024if size > 0 :return Trueelse:return False
修改 size 判断大小,目前默认为0
(2) 设置被存放在数据库中的图片记录将不被压缩,已经压缩的图片信息将被存放在数据库中
##########################################
# @function 判断图片大小是否被压缩过
# @description 如果图片信息存在于数据库中,则表明图片被压缩过,不需要再次压缩
# @param basename 待压缩图片名称
##########################################
def picIsCompressed(basename , dstFile):if selectTableCompressLog(basename , dstFile):#print(" images is already compressed which named " + basename + ' or path equals ' + dstFile)return Trueelse:return False
如果被压缩过的图片,也需要再次压缩,请将return True改为return False
使用Python快速压缩目录中图片相关推荐
- java zip 创建目录_Java实现Zip压缩目录中的所有文件
java中将一个文件夹下所有的文件压缩成一个文件,然import java.io.*; import java.util.zip.*; public class CompressD { // 缓冲 s ...
- Python快速找到列表中所有重复的元素
Python快速找到列表中所有重复的元素:https://blog.csdn.net/sinat_29957455/article/details/103886088 index方法 为了能够找到元素 ...
- python 找出图片中的差异点,python opencv对目录下图片进行去重的技巧
使用python opencv对目录下图片进行去重的方法 版本: 平台:ubuntu 14 / I5 / 4G内存 python版本:python2.7 opencv版本:2.13.4 依赖: 如果系 ...
- Python快速从视频中提取视频帧(多线程)
Python快速提取视频帧(多线程) 今天介绍一种从视频中抽取视频帧的方法,由于单线程抽取视频帧速度较慢,因此这里我们增加了多线程的方法. 1.抽取视频帧 抽取视频帧主要使用了 Opencv 模块. ...
- 【python 图片搜索】python 快速计算两个图片的相似度
一.图片相似度检测算法原理 我们日常中处理的数据大多数是文本和图片,既然文本有文本相似度,图片肯定也有图片相似度呀,是不是.下面介绍图片相似度检测的算法:检查两个图片的相似度,一个简单而快速的算法:感 ...
- Office - 如何压缩excel中图片大小
最近在处理user问题时候,遇到user有个excel文件有几百MB,在打开时候需要等很久,并且想通过outlook share给其他人时候,也因为文件过大被过滤无法发送. 经过check发现文件除了 ...
- python快速批量将jpg图片格式转为pgm格式
python快速批量将jpg或者png图片格式转为pgm格式. 代码里两个部分要改成你自己的路径,已经在代码备注. import os import cv2path = r'D:\DeepLearni ...
- 【python】使用python脚本将CelebA中图片按照 list_attr_celeba.txt 中属性处理(删除、复制、移动)
1.目的 CelebA中的照片有四十种属性,参见: [AI]CelebA数据介绍.下载及说明 根据需求从celebA中获取我们想要的图片,方法是将CelebA中图片按照 list_attr_celeb ...
- python图像文件压缩_python中如何实现图片压缩
python实现图片压缩的方法:1.导入Image包:2.使用get_size(file)命令获取图片文件的大小:3.使用[os.path.splitext()]方式拼接文件地址:然后压缩文件到指定大 ...
最新文章
- AngularJS2.0 教程系列(一)
- gdb调试工具的使用
- webpack4.x热更新,自动刷新
- linux编译安装memcached
- nginx_rtmp中解析sps和pps
- 今天的但我发现了幸福的超级玛丽,白萝卜的种子
- java 字符串 查找 多个_初学者求教,如何在字符串中查找多个子字符串的位置...
- 弥散阴影html,三步制作出这种精美弥散阴影
- 光敏传感器实验报告_光敏传感器光电特性研究实验报告.docx
- Laravel文档阅读笔记-Adding a Markdown editor to Laravel
- Linux(一):概述及环境搭建
- 云计算被指变相占土地 专家称去伪存真
- VoLTE和语音呼通率测试开发--执行脚本(三)
- 登陆失败:用户账户限制。可能的原因包括不允许空密码.........解决方案
- Linux怎么给命令创建别名,linux设置命令别名
- jquery.fn jquery.extend jquery.fn.extend
- Flutter 里的语法糖解析,知其所然方能潇洒舞剑,安卓开发面试题及答案
- 怎么看vue中某个插件是否安装成功_如何在谷歌中查看VUEX(谷歌浏览器中安装 vue调试工具 vue-devtools)...
- java基于springboot房屋租赁系统
- selenium 和 IP代理池