Python之如何调整图片的文件大小

 更新时间:2023年03月25日 09:06:48   作者:XerCis  
这篇文章主要介绍了Python之如何调整图片的文件大小问题,具有很好的参考价值,希望对大家有所帮助。

问题描述

Python调整图片文件的占用空间大小,而不是分辨率

1.jpg

1.jpg

图片大小为 8KB

 

减小文件大小

使用 PIL 模块

pip install Pillow

1. 减小图片质量

代码

import os
from PIL import Image


def 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 Image


def image_compress(filename, savename, targetsize):
    """图像压缩

    :param filename: 原图路径
    :param savename: 保存图片路径
    :param targetsize: 目标大小,单位为byte
    """
    image = Image.open(filename)
    size = os.path.getsize(filename)
    if size <= targetsize:
        return
    width, height = image.size
    num = (targetsize / size) ** 0.5
    width, height = round(width * num), round(height * num)
    image.resize((width, height)).save(savename)


if __name__ == '__main__':
    filename = '1.jpg'
    savename = 'result.jpg'
    targetsize = 2 * 1024
    image_compress(filename, savename, targetsize)

效果

增加文件大小

Windows

通过 subprocess 模块调用系统命令 fsutil file createnew filename filesize 创建指定大小的文件

再用 copy/b 命令合并数据到图片上

import os
import time
import subprocess

imagefile = '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 subprocess

imagefile = '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 Image


def 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)  # 缩小到2KB
    resize_picture_filesize(imagefile, 'increase.jpg', 800 * 1024)  # 放大到800KB

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • python基础教程项目四之新闻聚合

    python基础教程项目四之新闻聚合

    这篇文章主要为大家详细介绍了python基础教程项目四之新闻聚合,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04
  • Python中uuid模块的应用实例详解

    Python中uuid模块的应用实例详解

    这篇文章主要介绍了Python中uuid模块应用的相关资料,该模块提供了多种方法生成UUID,包括uuid1()、uuid3()、uuid4()和uuid5(),并解释了UUID的格式,UUID在数据库、分布式系统和网络协议中广泛应用,是处理唯一标识符的有力工具,需要的朋友可以参考下
    2024-11-11
  • Selenium鼠标与键盘事件常用操作方法示例

    Selenium鼠标与键盘事件常用操作方法示例

    这篇文章主要介绍了Selenium鼠标与键盘事件常用操作方法,结合实例形式分析了Selenium鼠标事件与键盘事件常见方法与相关使用技巧,需要的朋友可以参考下
    2018-08-08
  • python opencv的imread方法无法读取图片问题

    python opencv的imread方法无法读取图片问题

    这篇文章主要介绍了python opencv的imread方法无法读取图片问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • Python实现五子棋联机对战小游戏

    Python实现五子棋联机对战小游戏

    本文主要介绍了通过Python实现简单的支持联机对战的游戏——支持局域网联机对战的五子棋小游戏。废话不多说,快来跟随小编一起学习吧
    2021-12-12
  • Python实现遗传算法(虚拟机中运行)

    Python实现遗传算法(虚拟机中运行)

    遗传算法(GA)是最早由美国Holland教授提出的一种基于自然界的“适者生存,优胜劣汰”基本法则的智能搜索算法。本文主要介绍了如何通过Python实现遗传算法,感兴趣的同学可以看一看
    2021-11-11
  • TensorFlow-gpu和opencv安装详细教程

    TensorFlow-gpu和opencv安装详细教程

    这篇文章主要介绍了TensorFlow-gpu和opencv安装过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-06-06
  • Django实现学生管理系统

    Django实现学生管理系统

    这篇文章主要为大家详细介绍了Django实现学生管理系统,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-02-02
  • python中如何使用xml.dom.minidom模块读取解析xml文件

    python中如何使用xml.dom.minidom模块读取解析xml文件

    xml.dom.minidom模块应该是内置模块不用下载安装,本文给大家介绍python中如何使用xml.dom.minidom模块读取解析xml文件,感兴趣的朋友一起看看吧
    2023-10-10
  • Python实现的rsa加密算法详解

    Python实现的rsa加密算法详解

    这篇文章主要介绍了Python实现的rsa加密算法,结合完整实例形式分析了Python实现rsa加密算法的原理、步骤与相关操作技巧,需要的朋友可以参考下
    2018-01-01

最新评论