🛠️ToolsShed

이미지 형식 변환

PNG, JPEG, WebP 형식 간 이미지를 브라우저에서 즉시 변환.

자주 묻는 질문

코드 구현

# Convert between image formats using Pillow
# pip install Pillow

from PIL import Image
import os

def convert_image(input_path: str, output_path: str, format: str = None,
                  quality: int = 85, optimize: bool = True) -> None:
    """
    Convert an image to a different format.
    format: "JPEG", "PNG", "WEBP", "BMP", "TIFF", "ICO", "GIF"
    quality: 1-95, applies to JPEG and WebP
    """
    img = Image.open(input_path)
    output_format = format or os.path.splitext(output_path)[1].lstrip(".").upper()
    if output_format == "JPG":
        output_format = "JPEG"

    # JPEG requires RGB (no alpha)
    if output_format in ("JPEG",) and img.mode in ("RGBA", "P", "LA"):
        background = Image.new("RGB", img.size, (255, 255, 255))
        if img.mode in ("RGBA", "LA"):
            background.paste(img, mask=img.split()[-1])
        else:
            background.paste(img.convert("RGBA"), mask=img.convert("RGBA").split()[-1])
        img = background

    save_kwargs = {}
    if output_format == "JPEG":
        save_kwargs = {"quality": quality, "optimize": optimize, "progressive": True}
    elif output_format == "WEBP":
        save_kwargs = {"quality": quality, "method": 6, "lossless": False}
    elif output_format == "PNG":
        save_kwargs = {"optimize": optimize, "compress_level": 6}
    elif output_format == "ICO":
        # ICO supports multiple sizes in one file
        save_kwargs = {"sizes": [(16, 16), (32, 32), (64, 64), (128, 128)]}

    img.save(output_path, format=output_format, **save_kwargs)
    print(f"Saved: {output_path}")

# Batch convert an entire folder
import glob

def batch_convert(input_pattern: str, output_format: str, quality: int = 85):
    for path in glob.glob(input_pattern):
        base = os.path.splitext(path)[0]
        ext = output_format.lower().replace("jpeg", "jpg")
        out = f"{base}.{ext}"
        convert_image(path, out, format=output_format, quality=quality)
        print(f"Converted: {os.path.basename(path)} -> {os.path.basename(out)}")

# Examples
convert_image("photo.jpg", "photo.png")                    # JPEG -> PNG
convert_image("photo.jpg", "photo.webp", quality=80)      # JPEG -> WebP
convert_image("graphic.png", "graphic.jpg", quality=90)   # PNG -> JPEG
convert_image("logo.png", "favicon.ico")                   # PNG -> ICO (favicon)

# Batch: convert all PNGs to WebP
batch_convert("./images/*.png", "WEBP", quality=80)

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.