python 用于压缩文件夹中所有图像的python脚本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 用于压缩文件夹中所有图像的python脚本相关的知识,希望对你有一定的参考价值。

import piexif
import os
from PIL import Image

Copyright = "Paresh Sawant"  # add name of copyright holder
Artist = "Paresh Sawant"  # add name of attist
quality = 70


def get_images(path):
    os.chdir(path)
    return [f for f in os.listdir(path) if os.path.isfile(f)]
    pass


def get_all_images(root):
    valid_format = ['JPG', 'JPEG']
    response = []
    for path, subdirs, files in os.walk(root):
        for name in files:
            extension = name.split('.')[-1:][0].upper()
            if extension in valid_format:
                # print str(i) + " " + str(os.path.join(path, name))
                response.append(os.path.join(path, name))

    return response


def modify_exif(exif_dict):
    global Copyright, Artist

    if exif_dict is not 0:
        exif_dict['0th'][piexif.ImageIFD.Copyright] = Copyright
        exif_dict['0th'][piexif.ImageIFD.Artist] = Artist

    return exif_dict


def compress_image(imagefiles):
    file_count = len(imagefiles)
    count = 0
    for image_path in imagefiles:
        try:
            # image_path = path + '/' + image
            im = Image.open(image_path)

            try:
                exif_dict = modify_exif(piexif.load(im.info["exif"]))
                exif_bytes = piexif.dump(exif_dict)
            except KeyError:
                exif_bytes = None
                print "Exif data doesnot exist"

            if exif_bytes is None:
                im.save(image_path, "jpeg", quality=quality)
            else:
                im.save(image_path, "jpeg", exif=exif_bytes, quality=quality)

            im.close()
            pass
        except IOError:
            print "Not able to open file"
            pass
        finally:
            count = count + 1
            print("Processed: " + str(count) + "/" + str(file_count))


path = raw_input("Enter the path: ")
image_files = get_all_images(path)
compress_image(image_files)
# get_all_images(path)

以上是关于python 用于压缩文件夹中所有图像的python脚本的主要内容,如果未能解决你的问题,请参考以下文章

python 用于Google图像压缩实用程序zopflipng(PNG)和guetzli(JPG)的快速和脏的包装器。

Pytho之Django

如何在 python 中使用 S3TC/DXT 算法压缩 PNG 图像?

python颜色压缩的结果颜色比保存颜色深

Python 压缩图像

我如何在 React js 中压缩任何图像以及 Excel 和 CSV 文件