温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python怎么实现图片批量压缩

发布时间:2021-04-25 13:51:16 来源:亿速云 阅读:187 作者:小新 栏目:开发技术

这篇文章主要介绍python怎么实现图片批量压缩,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

python的数据类型有哪些?

python的数据类型:1. 数字类型,包括int(整型)、long(长整型)和float(浮点型)。2.字符串,分别是str类型和unicode类型。3.布尔型,Python布尔类型也是用于逻辑运算,有两个值:True(真)和False(假)。4.列表,列表是Python中使用最频繁的数据类型,集合中可以放任何数据类型。5. 元组,元组用”()”标识,内部元素用逗号隔开。6. 字典,字典是一种键值对的集合。7. 集合,集合是一个无序的、不重复的数据组合。

项目中大量用到图片加载,由于图片太大,加载速度很慢,因此需要对文件进行统一压缩

第一种

 一:安装包

python -m pip install Pillow

二:导入包

from PIL import Image
import os

三:获取图片文件的大小

def get_size(file):
    # 获取文件大小:KB
    size = os.path.getsize(file)
    return size / 1024

四:输出文件夹下的文件

dir_path = r'file_path'
items = os.listdir(dir_path)

for item in items:
    # print(item)
    path = os.path.join(dir_path, item)
    print(item)

五:压缩文件到指定大小,我期望的是150KB,step和quality可以修改到最合适的数值

def compress_image(infile, outfile=None, mb=150, step=10, quality=80):
    """不改变图片尺寸压缩到指定大小
    :param infile: 压缩源文件
    :param outfile: 压缩文件保存地址
    :param mb: 压缩目标,KB
    :param step: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址,压缩文件大小
    """
    if outfile is None:
        outfile = infile
    o_size = get_size(infile)
    if o_size <= mb:
        im = Image.open(infile)
        im.save(outfile)

    while o_size > mb:
        im = Image.open(infile)
        im.save(outfile, quality=quality)
        if quality - step < 0:
            break
        quality -= step
        o_size = get_size(outfile)

六:修改图片尺寸,如果同时有修改尺寸和大小的需要,可以先修改尺寸,再压缩大小

def resize_image(infile, outfile='', x_s=800):
    """修改图片尺寸
    :param infile: 图片源文件
    :param outfile: 重设尺寸文件保存地址
    :param x_s: 设置的宽度
    :return:
    """
    im = Image.open(infile)
    x, y = im.size
    y_s = int(y * x_s / x)
    out = im.resize((x_s, y_s), Image.ANTIALIAS)

    out.save(outfile)

七:运行程序

if __name__ == '__main__':
                      # 源路径      # 压缩后路径
    compress_image(r"file_path", r"E:\docs\2.JPG")
                    # 源路径      # 压缩后路径
    resize_image(r"file_path", r"E:\docs\3.JPG")

第二种

import os
from PIL import Image
import threading,time

def imgToProgressive(path):
    if not path.split('.')[-1:][0] in ['png','jpg','jpeg']:  #if path isn't a image file,return
        return
    if os.path.isdir(path):
        return
##########transform img to progressive
    img = Image.open(path)
    destination = path.split('.')[:-1][0]+'_destination.'+path.split('.')[-1:][0]
    try:
        print(path.split('\\')[-1:][0],'开始转换图片')
        img.save(destination, "JPEG", quality=80, optimize=True, progressive=True) #转换就是直接另存为
        print(path.split('\\')[-1:][0],'转换完毕')
    except IOError:
        PIL.ImageFile.MAXBLOCK = img.size[0] * img.size[1]
        img.save(destination, "JPEG", quality=80, optimize=True, progressive=True)
        print(path.split('\\')[-1:][0],'转换完毕')
    print('开始重命名文件')
    os.remove(path)
    os.rename(destination,path)

for d,_,fl in os.walk(os.getcwd()):    #遍历目录下所有文件
    for f in fl:
        try:
            imgToProgressive(d+'\\'+f)
        except:
            pass

以上是“python怎么实现图片批量压缩”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI