文章目录

  • 问题描述
  • 减小文件大小
    • 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

参考文献

  1. Python批量直接修改图片存储大小脚本
  2. How do I install PythonMagick for Python 3.5
  3. PythonMagick GitHub
  4. ImageMagick Documentation
  5. DOS Command: COPY
  6. python给png图片写入无用数据从而改变其md5
  7. Create a File of Specific Size in Windows 10
  8. How To Create Files Of A Certain Size In Linux
  9. Python执行系统命令
  10. How can I copy several binary files into one file on a Linux system?
  11. How to compress a picture less than a limit file size using python PIL library?

Python调整图片的文件大小相关推荐

  1. Python调整图片大小并保存调整后的图像

    Python调整图片大小并保存调整后的图像 目录 Python调整图片大小并保存调整后的图像 #原始图像

  2. 使用Python调整图片尺寸(大小)

    凯哥英语视频 使用Python调整图片尺寸(大小) python有一个图像处理库--PIL,可以处理图像文件.PIL提供了功能丰富的方法,比如格式转换.旋转.裁剪.改变尺寸.像素处理.图片合并等等等等 ...

  3. python调整图片亮度_python 调整图片亮度的示例

    实现效果 实现代码 import matplotlib.pyplot as plt from skimage import io file_name='D:/2020121173119242.png' ...

  4. python调整图片亮度_python调整图片亮度的示例

    这篇文章我们来讲一下在网站建设中,python调整图片亮度的示例.本文对大家进行网站开发设计工作或者学习都有一定帮助,下面让我们进入正文. 实现效果 实现代码 import matplotlib.py ...

  5. python调整图片大小不覆盖exif_python---基础知识回顾(十一)图像处理模块PIL

    前戏: 虽然PIL没有入OpenCV那样强大的功能,但是所提供的功能,在一般的图像处理中足够使用. 图像类别: 计算机绘图中有两类图像:一类是矢量图,另一类是点阵图(位图) 矢量图: 基于计算机数字对 ...

  6. 使用python调整图片大小

    对单一图片进行处理: 需要调整的图片: 示例代码: from PIL import Imagedef image_processing():# 待处理图片路径img_path = Image.open ...

  7. python调整图片大小reshape_将不同大小的图像调整为28x28图像并将其转换为一个csvfi...

    我有两个文件夹,里面装满了不同大小的图片(每个大约2000个文件).我需要所有的28x28格式.之后,我需要将每个文件夹的所有图像转换为一个csv文件.你知道我怎么做吗?我是python的初学者,所以 ...

  8. python调整图片大小reshape_scipy.misc.imresize改变图像的大小

    scipy.misc.imresize( arr, size, interp='bilinear', mode=None) resize an image.改变图像大小并且隐藏归一化到0-255区间的 ...

  9. python调整图片色相,对应ps的色相值

    ps的色相值调整是相对原图的基础左右调整的,这里最后的效果是对应ps色相调整的效果,ps的ctrl+u弹出调节色相窗口 def change_color():image: PngImageFile = ...

  10. python调整图片大小,png,jpg均使用

    import os from PIL import Imagedef image_processing():# 待处理图片路径下的所有文件名字all_file_names = os.listdir(' ...

最新文章

  1. php保存base64数据
  2. 开始使用Spring Cloud实战微服务
  3. websocket后台推送数据
  4. 生效linux内核,Linux内核
  5. java计算出生到现在经历了多少天
  6. C++(STL):33---hash_set、hash_map、hash_multiset、hash_multimap源码剖析
  7. mysql一列数据转为一行_MySQL高性能优化规范建议,速度收藏
  8. RHEL 8 - 安装 webconsole
  9. lisp钢管_技术专栏集合管道模式(上)
  10. 1002 C语言输入解决方案
  11. java 运行时异常 处理_如何在Java中处理运行时异常?
  12. python中delta是什么意思_python – 根据dataframe中的值计算delta
  13. 使用 Redis 实现一个轻量级的搜索引擎,牛逼啊!
  14. 智能家居的新篇章-PHILIPS HUE
  15. Redis分布式锁为什么要设置超时时间
  16. c语言生日创意代码_C语言如何编程生日快乐代码
  17. Java学习路线(转)
  18. SqlServer无法连接服务器
  19. 更换计算机名后打不开PPT,ppt视频换电脑无法播放怎么办
  20. c# 获取本机IP地址

热门文章

  1. 项目发布到Tomcat后,网页图片不显示
  2. 基础物理-物质的组成
  3. 基于算力驱动、数据与功能协同的分布式动态(协同)渲染/功能运行时
  4. 虾米音乐明年1月将关闭?网友集体跪求
  5. Myeclipse 6.0 regester NO
  6. 技术指南 | 理解零知识证明算法之Zk-stark
  7. Marlin2.0.9 Configuration_adv.h详解
  8. python图片标记_用python找出那些被“标记”的照片
  9. 抖音短视频如何去水印?
  10. 拉钩教育大前端课程学习-半年总结