Python调整图片的文件大小
文章目录
- 问题描述
- 减小文件大小
- 1. 减小图片质量
- 2. 减小图片尺寸
- 增加文件大小
- 封装
- 参考文献
问题描述
Python调整图片文件的占用空间大小,而不是分辨率
1.jpg
图片大小为 8KB
减小文件大小
使用 PIL
模块
pip install Pillow
1. 减小图片质量
代码
import os
from PIL import Imagedef compress_under_size(imagefile, targetfile, targetsize):"""压缩图片尺寸直到某一尺寸:param imagefile: 原图路径:param targetfile: 保存图片路径:param targetsize: 目标大小,单位byte"""currentsize = os.path.getsize(imagefile)for quality in range(99, 0, -1): # 压缩质量递减if currentsize > targetsize:image = Image.open(imagefile)image.save(targetfile, optimize=True, quality=quality)currentsize = os.path.getsize(targetfile)if __name__ == '__main__':imagefile = '1.jpg' # 图片路径targetfile = 'result.jpg' # 目标图片路径targetsize = 2 * 1024 # 目标图片大小compress_under_size(imagefile, targetfile, targetsize) # 将图片压缩到2KB
效果
注意!无法实现图片无限压缩,若文件太小,辨识度也会大大降低
2. 减小图片尺寸
import os
from PIL import Imagedef image_compress(filename, savename, targetsize):"""图像压缩:param filename: 原图路径:param savename: 保存图片路径:param targetsize: 目标大小,单位为byte"""image = Image.open(filename)size = os.path.getsize(filename)if size <= targetsize:returnwidth, height = image.sizenum = (targetsize / size) ** 0.5width, height = round(width * num), round(height * num)image.resize((width, height)).save(savename)if __name__ == '__main__':filename = '1.jpg'savename = 'result.jpg'targetsize = 2 * 1024image_compress(filename, savename, targetsize)
效果
增加文件大小
Windows
通过 subprocess
模块调用系统命令 fsutil file createnew filename filesize
创建指定大小的文件
再用 copy/b
命令合并数据到图片上
import os
import time
import subprocessimagefile = '1.jpg' # 图片路径
targetfile = 'result.jpg' # 目标图片路径
targetsize = 10 * 1024 * 1024 # 目标图片大小tempfile = str(int(time.time())) # 临时文件路径
tempsize = str(targetsize - os.path.getsize(imagefile)) # 临时文件大小
subprocess.run(['fsutil', 'file', 'createnew', tempfile, tempsize]) # 创建临时文件
subprocess.run(['copy/b', '{}/b+{}/b'.format(imagefile, tempfile), targetfile], shell=True) # 合并生成新图片
os.remove(tempfile)
Linux
通过 subprocess
模块调用系统命令 fallocate -l filesize filename
创建指定大小的文件
再用 cat >
命令合并数据到图片上
import os
import time
import subprocessimagefile = '1.jpg' # 图片路径
targetfile = 'result.jpg' # 目标图片路径
targetsize = 10 * 1024 * 1024 # 目标图片大小tempfile = str(int(time.time())) # 临时文件路径
tempsize = str(targetsize - os.path.getsize(imagefile)) # 临时文件大小
subprocess.run(['fallocate', '-l', tempsize, tempfile]) # 创建临时文件
subprocess.run('cat {} {} > {}'.format(imagefile, tempfile, targetfile), shell=True) # 合并生成新图片
os.remove(tempfile)
效果
图片的分辨率没变
封装
import os
import time
import platform
import subprocess
from PIL import Imagedef resize_picture_filesize(imagefile, targetfile, targetsize):"""调整图片文件大小:param imagefile: 原图路径:param targetfile: 保存图片路径:param targetsize: 目标文件大小,单位byte"""currentsize = os.path.getsize(imagefile) # 原图文件大小if currentsize > targetsize: # 需要缩小for quality in range(99, 0, -1): # 压缩质量递减if currentsize > targetsize:image = Image.open(imagefile)image.save(targetfile, optimize=True, quality=quality)currentsize = os.path.getsize(targetfile)else: # 需要放大system = platform.system()tempfile = str(int(time.time())) # 临时文件路径tempsize = str(targetsize - os.path.getsize(imagefile)) # 临时文件大小if system == 'Windows':subprocess.run(['fsutil', 'file', 'createnew', tempfile, tempsize]) # 创建临时文件subprocess.run(['copy/b', '{}/b+{}/b'.format(imagefile, tempfile), targetfile], shell=True) # 合并生成新图片elif system == 'Linux':subprocess.run(['fallocate', '-l', tempsize, tempfile]) # 创建临时文件subprocess.run('cat {} {} > {}'.format(imagefile, tempfile, targetfile), shell=True) # 合并生成新图片os.remove(tempfile)if __name__ == '__main__':imagefile = '1.jpg' # 8KB的图片resize_picture_filesize(imagefile, 'reduce.jpg', 2 * 1024) # 缩小到2KBresize_picture_filesize(imagefile, 'increase.jpg', 800 * 1024) # 放大到800KB
参考文献
- Python批量直接修改图片存储大小脚本
- How do I install PythonMagick for Python 3.5
- PythonMagick GitHub
- ImageMagick Documentation
- DOS Command: COPY
- python给png图片写入无用数据从而改变其md5
- Create a File of Specific Size in Windows 10
- How To Create Files Of A Certain Size In Linux
- Python执行系统命令
- How can I copy several binary files into one file on a Linux system?
- How to compress a picture less than a limit file size using python PIL library?
Python调整图片的文件大小相关推荐
- Python调整图片大小并保存调整后的图像
Python调整图片大小并保存调整后的图像 目录 Python调整图片大小并保存调整后的图像 #原始图像
- 使用Python调整图片尺寸(大小)
凯哥英语视频 使用Python调整图片尺寸(大小) python有一个图像处理库--PIL,可以处理图像文件.PIL提供了功能丰富的方法,比如格式转换.旋转.裁剪.改变尺寸.像素处理.图片合并等等等等 ...
- python调整图片亮度_python 调整图片亮度的示例
实现效果 实现代码 import matplotlib.pyplot as plt from skimage import io file_name='D:/2020121173119242.png' ...
- python调整图片亮度_python调整图片亮度的示例
这篇文章我们来讲一下在网站建设中,python调整图片亮度的示例.本文对大家进行网站开发设计工作或者学习都有一定帮助,下面让我们进入正文. 实现效果 实现代码 import matplotlib.py ...
- python调整图片大小不覆盖exif_python---基础知识回顾(十一)图像处理模块PIL
前戏: 虽然PIL没有入OpenCV那样强大的功能,但是所提供的功能,在一般的图像处理中足够使用. 图像类别: 计算机绘图中有两类图像:一类是矢量图,另一类是点阵图(位图) 矢量图: 基于计算机数字对 ...
- 使用python调整图片大小
对单一图片进行处理: 需要调整的图片: 示例代码: from PIL import Imagedef image_processing():# 待处理图片路径img_path = Image.open ...
- python调整图片大小reshape_将不同大小的图像调整为28x28图像并将其转换为一个csvfi...
我有两个文件夹,里面装满了不同大小的图片(每个大约2000个文件).我需要所有的28x28格式.之后,我需要将每个文件夹的所有图像转换为一个csv文件.你知道我怎么做吗?我是python的初学者,所以 ...
- python调整图片大小reshape_scipy.misc.imresize改变图像的大小
scipy.misc.imresize( arr, size, interp='bilinear', mode=None) resize an image.改变图像大小并且隐藏归一化到0-255区间的 ...
- python调整图片色相,对应ps的色相值
ps的色相值调整是相对原图的基础左右调整的,这里最后的效果是对应ps色相调整的效果,ps的ctrl+u弹出调节色相窗口 def change_color():image: PngImageFile = ...
- python调整图片大小,png,jpg均使用
import os from PIL import Imagedef image_processing():# 待处理图片路径下的所有文件名字all_file_names = os.listdir(' ...
最新文章
- php保存base64数据
- 开始使用Spring Cloud实战微服务
- websocket后台推送数据
- 生效linux内核,Linux内核
- java计算出生到现在经历了多少天
- C++(STL):33---hash_set、hash_map、hash_multiset、hash_multimap源码剖析
- mysql一列数据转为一行_MySQL高性能优化规范建议,速度收藏
- RHEL 8 - 安装 webconsole
- lisp钢管_技术专栏集合管道模式(上)
- 1002 C语言输入解决方案
- java 运行时异常 处理_如何在Java中处理运行时异常?
- python中delta是什么意思_python – 根据dataframe中的值计算delta
- 使用 Redis 实现一个轻量级的搜索引擎,牛逼啊!
- 智能家居的新篇章-PHILIPS HUE
- Redis分布式锁为什么要设置超时时间
- c语言生日创意代码_C语言如何编程生日快乐代码
- Java学习路线(转)
- SqlServer无法连接服务器
- 更换计算机名后打不开PPT,ppt视频换电脑无法播放怎么办
- c# 获取本机IP地址
热门文章
- 项目发布到Tomcat后,网页图片不显示
- 基础物理-物质的组成
- 基于算力驱动、数据与功能协同的分布式动态(协同)渲染/功能运行时
- 虾米音乐明年1月将关闭?网友集体跪求
- Myeclipse 6.0 regester NO
- 技术指南 | 理解零知识证明算法之Zk-stark
- Marlin2.0.9 Configuration_adv.h详解
- python图片标记_用python找出那些被“标记”的照片
- 抖音短视频如何去水印?
- 拉钩教育大前端课程学习-半年总结