python 일괄 압축 그림 스 크 립 트

간단 한 소개
Python 으로 그림 을 대량으로 압축 하여 폴 더 나 그림 을 직접 끌 어 다 놓 으 면 됩 니 다.
필요
Python 3
Pillow(pip install pillow 로 설치 하면 됩 니 다)
용법
폴 더 나 그림 을 직접 끌 어 들 이면 됩 니 다.폴 더 를 끌 어 다 놓 으 면 하위 폴 더 를 옮 겨 다 니 며 모든 그림 을 압축 합 니 다.
압축 된 파일 은 원래 의 파일 을 직접 교체 합 니 다.파일 이름 은 변 하지 않 고 크기 는 변 하지 않 으 며 압축 의 질 만 바 꿉 니 다.
파일 의 시작 에 두 개의 변수 가 있 습 니 다.
SIZE_CUT=4 는 4MB 이상 의 그림 을 압축 한 다 는 뜻 이다.
QUALITY=90 은 압축 질량 90 을 나타 내 는데 이 질량 은 기본적으로 사람들의 눈 에 어떤 차이 가 있 는 지 알 수 없 으 며 원래 10M 이 었 던 많은 그림 들 이 반 으로 압축 될 수 있다.80 이하 의 품질 은 아마 그다지 좋 지 않 을 것 이다.
코드

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

# Created by Mario Chen, 01.04.2021, Shenzhen
# My Github site: https://github.com/Mario-Hero

import sys
import os
from PIL import Image

SIZE_CUT = 4   # picture over this size should be compressed. Units: MB
QUALITY = 90  # 90 is good, this number should not be smaller than 80.


def isPic(name):
    namelower = name.lower()
    return namelower.endswith("jpeg") or namelower.endswith("jpg") or namelower.endswith("png")


def compressImg(file):
    #print("The size of", file, "is: ", os.path.getsize(file))
    im = Image.open(file)
    im.save(file, quality=QUALITY)


def compress(folder):
    try:
        if os.path.isdir(folder):
            print(folder)
            file_list = os.listdir(folder)
            for file in file_list:
                if os.path.isdir(folder+"/"+file):
                    #print(folder +"/"+ file)
                    compress(folder +"/"+file)
                else:
                    if isPic(file):
                        if os.path.getsize(folder + "/" + file) > (SIZE_CUT * 1024 * 1024):
                            compressImg(folder + "/" + file)
                            print(file)
        else:
            if isPic(folder):
                if os.path.getsize(folder) > (SIZE_CUT * 1024 * 1024):
                    compressImg(folder)
    except BaseException:
        return


if __name__ == '__main__':
    for folder in sys.argv:
        #print(folder)
        compress(folder)
    print("Finish.")
    #os.system("pause")
실현 효과

압축 후 크기

다른 그림 압축 실현 방식
디 렉 터 리 에 있 는 그림 을 자동 으로 옮 겨 다 닙 니 다.

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 대량 압축 그림 의 스 크 립 트 에 대한 상세 한 내용 입 니 다.python 대량 압축 그림 에 대한 자 료 는 다른 관련 글 을 주목 하 십시오!

좋은 웹페이지 즐겨찾기