티스토리 뷰

공부

[python] image resize code

승가비 2024. 1. 6. 00:35
728x90
from PIL import Image
import os


def bak(path):
    copy(path, f"{path}.bak")


def rollback(path):
    copy(f"{path}.bak", path)
    os.remove(f"{path}.bak")

def copy(src, dst):
    try:
        with open(src, 'rb') as src, open(dst, 'wb') as f:
            f.write(src.read())
    except:
        pass


def check(path):
    try:
        new = os.path.getsize(path)
        old = os.path.getsize(f"{path}.bak")

        if new > old:
            rollback(path)
            print(f"[rollback] ({new} > {old}); {path}")
    except:
        pass


def png(path, quality=65, compress_level=9):
    try:
        bak(path)

        Image.open(path).save(
            path,
            "PNG",
            quality=quality,
            compress_level=compress_level,
            optimize=True,
        )
    except:
        print(f"[error] {path}")


def jpg(path, quality=65, compress_level=9):
    try:
        bak(path)

        Image.open(path).save(
            path,
            "JPEG",
            quality=quality,
            compress_level=compress_level,
            optimize=True,
        )
    except:
        print(f"[error] {path}")


def all(dir):
    for filename in os.listdir(dir):
        path = os.path.join(dir, filename)

        if os.path.isdir(path):
            all(path)
            continue

        lower = filename.lower()
        if lower.endswith(".png"):
            png(path)
        elif lower.endswith(".jpg") or lower.endswith(".jpeg"):
            jpg(path)

        check(path)


if __name__ == "__main__":
    dir = "/Users/seunggabi/Downloads/uploads"
    all(dir)

https://stackoverflow.com/questions/54570614/how-can-i-reduce-the-file-size-of-a-png-image-without-changing-its-dimensions

 

How can I reduce the file size of a PNG image without changing its dimensions?

I want to reduce the file size of a PNG file using Python. I have gone through a lot of material on the internet, but I could not find anything where I would reduce the file size for an image without

stackoverflow.com

 

728x90

'공부' 카테고리의 다른 글

[thymeleaf] layout:decorator & layout:decorate  (0) 2024.01.06
[tomcat] context.xml  (0) 2024.01.06
[spring] jasypt  (0) 2024.01.06
[jwt]  (0) 2024.01.02
[intelliJ] properties  (0) 2024.01.02
댓글