Python图片有损压缩

电脑技术 电脑技术 1205 人阅读 | 0 人回复 | 2022-04-12

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x

# run this in any directory
# add -v for verbose
# get Pillow (fork of PIL) from
# pip before running -->
# pip install Pillow
  
# import required libraries
import os
import sys
from PIL import Image
  
# define a function for
# compressing an image
def compressMe(file, verbose = False):
   
      # Get the path of the file
    filepath = os.path.join(os.getcwd(),
                            file)
      
    # open the image
    picture = Image.open(filepath)
      
    # Save the picture with desired quality
    # To change the quality of image,
    # set the quality variable at
    # your desired level, The more
    # the value of quality variable
    # and lesser the compression
    picture.save("Compressed_"+file,
                 "JPEG",
                 optimize = True,
                 quality = 10)
    return
  
# Define a main function
def main():
   
    verbose = False
      
    # checks for verbose flag
    if (len(sys.argv)>1):
        
        if (sys.argv[1].lower()=="-v"):
            verbose = True
                     
    # finds current working dir
    cwd = os.getcwd()
  
    formats = ('.jpg', '.jpeg')
      
    # looping through all the files
    # in a current directory
    for file in os.listdir(cwd):
        
        # If the file format is JPG or JPEG
        if os.path.splitext(file)[1].lower() in formats:
            print('compressing', file)
            compressMe(file, verbose)
  
    print("Done")
  
# Driver code
if __name__ == "__main__":
    main()
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则