inspiration

블로그 최적화를 위해서, webp 포맷을 자주 사용한다. 그런데, 매번 온라인상에서 이미지를 올려서 변환하기도, 포토샵을 사용하기도 좀 그렇다.

구글 dev 사이트에서 변환 프로그램을 다운받았는데, 매번 cmd를 입력해줘야 하는 방식이다.
이 또한 귀찮으니, 파이썬으로 간단한 프로그램을 짜본다.



execution

프로그램 위치는 아래와 같이 구성하고, 당연히 python 실행은 윈도우즈 path에 걸어서 어디서든 동작하게 만들어 둔다. 샘플코드는 다음과 같다.

아래 코드가 저장된 python.py 파일
└─ ─ ─ ─ ─ ─ libwebp-1.4.0-windows-x64 폴더



바탕화면이든 어디든 batch 파일을 써서, 해당 python 프로그램이 실행될 수 있도록 해주면 끝이다.
단, 본인의 python에 아래 패키지들이 사전에 install 되어있어야 한다.

첫번째 탐색기가 뜨면 변환하고 싶은 파일을 선택해주고, 두번째 탐색기에서는 저장할 폴더를 선택해주면 된다.
물론 코드를 좀 수정해서, 타겟 폴더를 원하는 폴더에 고정해줄 수도 있다.

import os
import tkinter
from tkinter import filedialog

from PIL import Image
from PIL.ExifTags import TAGS

def get_image_width(image_path):
    # Open the image
    with Image.open(image_path) as img:
        # Get the width
        return img.width            

if __name__ == '__main__':

    # 폴더선택
    root = tkinter.Tk()
    root.withdraw()

    file_path = filedialog.askopenfilenames(
        parent=root, initialdir="/", title='Please select target files') # 대상파일선택

    dir_path = filedialog.askdirectory(
        parent=root, initialdir="/", title='Please select saving directory') # 저장폴더선택

    programPath = os.getcwd() + "/libwebp-1.4.0-windows-x64/bin/cwebp.exe" # 프로그램저장경로(수정!!!)
   
    for fileConvertion in file_path :        
       
        filename = os.path.basename(fileConvertion)        
        name, extension = os.path.splitext(filename, )        

        # Example usage
        image_path = fileConvertion
        print(image_path)
        width = get_image_width(image_path)
        print(f"Image width: {width}")
        if width > 700 :
            command = programPath + ' "' + fileConvertion + '" -q 100 -resize 700 0 -o "' + dir_path + '/' + name + '.webp"'
            print(command)
        else :
            command = programPath + ' "' + fileConvertion + '" -q 100 -o "' + dir_path + '/' + name + '.webp"'
   
        os.system(command=command)


그런데, webp 변환 이후 결과물의 이미지 퀄리티가 떨어져 보이는건 느낌적인 느낌일까?

단지 느낌만은 아니다.
전반적으로 레드 컬러톤이 다운된다는 것을 알게 되었다. 해당 프로그램 설명페이지에 있는 수많은 옵션들을 건드려봐야 알 수 있을 것 같기는하다.



옵션 업데이트, exif 정보 유지

위에 언급했듯 변환을 하면서, 레드 컬러의 열화가 있고, exif정보가 날아가는 문제가 있었는데, 옵션조정과 exif 프로그램을 추가하여 정보를 유지하도록 했다.

아래 코드가 저장된 python.py 파일
└─ ─ ─ ─ ─ ─ libwebp-1.4.0-windows-x64 폴더
└─ ─ ─ ─ ─ ─ exiftool-13.12_64 폴더



파이썬 실행코드를 아래와 같이 수정해봤다.

✶ 메뉴얼을 보고, 화질에 영향을 준다는 요소들을 전부 제외하거나 추가를 해봤지만, 옵션 조정으로 레드컬러를 보존하는 것도 신통치 않은 것 같다.
✶ exiftool 프로그램을 다운 받은 뒤 동일한 경로에 추가해서 exif 정보 유지를 하도록 했는데 이건 어느정도 성공한 듯하다.

샘플코드는 다음과 같다. 수많은 옵션 주석이 나의 간절함을 나타내는 듯하다.

import os
import tkinter
from tkinter import filedialog

from PIL import Image
from PIL.ExifTags import TAGS

def get_image_width(image_path):
    # Open the image
    with Image.open(image_path) as img:
        # Get the width
        return img.width
   
def get_image_height(image_path):
    # Open the image
    with Image.open(image_path) as img:
        # Get the width
        return img.height
   
if __name__ == '__main__':

    # 폴더선택
    root = tkinter.Tk()
    root.withdraw()

    file_path = filedialog.askopenfilenames(
        parent=root, initialdir="/", title='Please select target files')

    dir_path = filedialog.askdirectory(
        parent=root, initialdir="/", title='Please select saving directory')

    programPath = os.getcwd() + "/libwebp-1.4.0-windows-x64/bin/cwebp.exe"
    programPath_exif = os.getcwd() + "/exiftool-13.12_64/exiftool.exe"
   
    for fileConvertion in file_path :        
       
        filename = os.path.basename(fileConvertion)        
        name, extension = os.path.splitext(filename, )        

        # Example usage
        image_path = fileConvertion
       
        width = get_image_width(image_path)
        height = get_image_height(image_path)       
       
        if width > 702 :
            changeheight =  int(round(height * 702 / width))           
            command = programPath + ' "' + fileConvertion + '" -lossless -z 0 -exact -m 6 -resize 702 "' + str(changeheight) + '" -o "' + dir_path + '/' + name + '.webp"'
            # command = programPath + ' "' + fileConvertion + '" -z 0 -exact -m 6 -noalpha -o "' + dir_path + '/' + name + '.webp"'
            # command = programPath + ' "' + fileConvertion + '" -z 0 -exact -m 6 -resize 700 0 -noalpha -o "' + dir_path + '/' + name + '.webp"'
            # command = programPath + ' "' + fileConvertion + '" -lossless -z 0 -exact -m 6 -resize 700 0 -o "' + dir_path + '/' + name + '.webp"'
            # command = programPath + ' "' + fileConvertion + '" -lossless -q 100 -resize 700 0 -o "' + dir_path + '/' + name + '.webp"'
            # command = programPath + ' "' + fileConvertion + '" -q 100 -m 6 -preset photo -short -resize 700 0 -o "' + dir_path + '/' + name + '.webp"'
            command_exif = programPath_exif + ' -TagsFromFile' + ' "' + fileConvertion + '" "' + dir_path + '/' + name + '.webp"'
        else :
            command = programPath + ' "' + fileConvertion + '" -lossless -z 0 -exact -m 6 -o "' + dir_path + '/' + name + '.webp"'
            # command = programPath + ' "' + fileConvertion + '" -z 0 -exact -m 6 -noalpha -o "' + dir_path + '/' + name + '.webp"'
            # command = programPath + ' "' + fileConvertion + '" -lossless -z 0 -exact -m 6 -o "' + dir_path + '/' + name + '.webp"'
            # command = programPath + ' "' + fileConvertion + '" -lossless -q 100 -o "' + dir_path + '/' + name + '.webp"'
            # command = programPath + ' "' + fileConvertion + '" -q 100 -m 6 -preset photo -short -o "' + dir_path + '/' + name + '.webp"'
            command_exif = programPath_exif + ' -TagsFromFile' + ' "' + fileConvertion + '" "' + dir_path + '/' + name + '.webp"'
               
        os.system(command=command)
        os.system(command=command_exif)


일단은 여기까지.

끝.