Python으로 디렉터리 내 이미지 한 번에 변경하기

In: Programming

5 Jan 2010

bmp 이미지 리소스를 png로 변경하기 위해 간단히 만든 Python 스크립트.
사실 간단히는 아니고, os.path 사용법과 PIL(Python Image Library)이라는 걸 찾느라 30분 날려 먹었다.

변경할 때, 파일 포맷을 좀 더 세부적으로 저장할 수 있는 옵션이 save 함수에 있긴 한데, 그냥 디폴트 변환으로도 별 무리 없었다.

# -*- coding: utf-8 -*-
 
import sys
import os, glob
import Image  
 
srcDir = "c:/temp"
destDir = "c:/temp/converted"
 
for inPath in glob.glob(os.path.join(srcDir, "*.bmp")):
    try:
        image = Image.open(inPath)
 
        (filePath, fileName) = os.path.split(inPath)
        (shortName, extension) = os.path.splitext(fileName)
        outPath = os.path.join(destDir, "{0}.png".format(shortName))
 
        image.save(outPath)
    except:
        print("Can't convert {0}".format(inPath))
        continue

몰랐는데, Python 2.6 부터는 문자열에 format 함수가 생겨서 마치 C#의 형식화처럼 문자열을 처리할 수 있었다.

Comments are closed.

Categories