iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python怎么调整图片的文件大小
  • 915
分享到

Python怎么调整图片的文件大小

2023-07-05 16:07:27 915人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

本篇内容主要讲解“python怎么调整图片的文件大小”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Python怎么调整图片的文件大小”吧!问题描述Python调整图片文件的占用空间大小,而不是分

本篇内容主要讲解“python怎么调整图片的文件大小”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习Python怎么调整图片的文件大小”吧!

    问题描述

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

    jpg

    Python怎么调整图片的文件大小

    图片大小为 8KB

    减小文件大小

    使用 PIL 模块

    pip install Pillow

    1. 减小图片质量

    代码

    import osfrom 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

    效果

    Python怎么调整图片的文件大小

    注意!无法实现图片无限压缩,若文件太小,辨识度也会大大降低

    2. 减小图片尺寸

    import osfrom 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:        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)

    效果

    Python怎么调整图片的文件大小

    增加文件大小

    Windows

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

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

    import osimport timeimport 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 osimport timeimport 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)

    效果

    Python怎么调整图片的文件大小

    图片的分辨率没变

    封装

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

    到此,相信大家对“Python怎么调整图片的文件大小”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

    --结束END--

    本文标题: Python怎么调整图片的文件大小

    本文链接: https://www.lsjlt.com/news/353385.html(转载时请注明来源链接)

    有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

    本篇文章演示代码以及资料文档资料下载

    下载Word文档到电脑,方便收藏和打印~

    下载Word文档
    软考高级职称资格查询
    编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
    • 官方手机版

    • 微信公众号

    • 商务合作