본문 바로가기
풀스택 개발/기타

티스토리 블로그 백업 데이터의 이미지를 webP형식으로 한 번에 바꾸기

by act2 2025. 1. 23.
728x90

티스토리 블로그를 백업하고 궁금했던 점 한 가지는...

'이미지가 jpg와 png 형식으로 되어있는데, 이걸 webp 형식으로 변환할 수 없을까?' 하는 것이었습니다. 

글이 약 6,800여 개가 되니, 이걸 하나하나 수작업으로 바꿀 수도 없고...

 

궁금해서 GPT와 대화를 하면서, 그 해답을 찾았습니다.

아래처럼 말이죠.

 

티스토리를 백업한 압축파일을 풀고,

그때 생긴 디렉토리 안에다. script_name.py라는 이름으로 파일을 하나 만들어 넣어줬습니다.

그리고 실행을 하니, 지금 열심히 돌아가고 있습니다.

 

jpg 파일과 png 파일을 webP 파일로 바꾸고, 

원래 있던 이미지 파일은 자동으로 삭제합니다. 

 

from PIL import Image
import os
from pathlib import Path
import time


def retry_remove(file_path, max_attempts=5):
    for attempt in range(max_attempts):
        try:
            os.remove(file_path)
            print(f"Deleted original file: {file_path}")
            return
        except PermissionError:
            print(f"Attempt {attempt + 1}: Failed to delete {file_path}. Retrying...")
            time.sleep(1)
    print(f"Failed to remove file after {max_attempts} attempts: {file_path}")


def convert_to_webp(source):
    destination = source.with_suffix(".webp")
    try:
        with Image.open(source) as image:
            image.save(destination, format="webp")
        print(f"Converted: {source} to {destination}")

        # 파일 핸들이 완전히 해제되도록 잠시 대기
        time.sleep(0.5)

        # 원본 파일 삭제 시도
        retry_remove(source)
    except Exception as e:
        print(f"Error processing {source}: {e}")


# 현재 스크립트 파일의 위치를 기준으로 base_dir 설정
base_dir = Path(__file__).parent

print(f"Searching for images in: {base_dir}")

conversion_count = 0

# 현재 폴더 내의 각 글 폴더 순회
for post_folder in base_dir.iterdir():
    if post_folder.is_dir() and post_folder.name != "__pycache__":
        # 각 글 폴더 내의 이미지 폴더 경로
        image_folder = post_folder / "img"  # "images"를 "img"로 변경

        if image_folder.exists():
            print(f"Checking folder: {image_folder}")
            for image_file in image_folder.glob("*"):
                if image_file.suffix.lower() in (".png", ".jpg", ".jpeg"):
                    convert_to_webp(image_file)
                    conversion_count += 1

if conversion_count > 0:
    print(f"Conversion and cleanup complete. Converted {conversion_count} images.")
else:
    print("No images found for conversion.")

print(f"Script executed from: {os.getcwd()}")

 

검색엔진에서 차세대 이미지 형식을 사용하라는 말을 하도 들어서, 

어찌할까 걱정했는데, 이런 방법으로 해결할 수 있군요.

 

이미지 파일을 webP 형식으로 변환하면,

SEO에도 좋고 파일 크기도 작아져서 저장 용량도 절약할 수 있어 일석이조의 효과가 있습니다.

 

저처럼 이미지 파일 변환 때문에 고민이셨던 분은, 

위 파이썬 코드를 활용해 한 번에 이미지를 변환해 보시기 바랍니다.

728x90