根据任意图片,生成指定大小的图片文件

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 = r'C:\1\1.png'  # 221KB的图片
    resize_picture_filesize(imagefile, 'reduce.jpg', 2 * 1024)  # 缩小到2KB
    resize_picture_filesize(imagefile, 'increase.png', 10 * 1024 * 1024)  # 放大到10M
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

初遇我ㄖ寸の热情呢?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值