웹페이지 운영/블로그 자동화

블로그 자동화를 위한 썸네일 자동 생성 파이썬 스크립트

공무원 봉급 2022. 5. 31. 00:53

 

본 페이지에서는 블로그 자동화를 위한 이미지를 자동으로 생성하는 방법에 대해서 설명합니다. 추가적으로 파이썬 스크립트를 예제로 제공합니다.

 

블로그 자동화 절차

필자의 배우자의 독촉으로 블로그 자동화 작업을 진행하게 되었습니다. 여러 홈페이지에서 필요한 정보를 수집하고, 그 정보를 바탕으로 웹서버에 자동으로 글을 쓰는 방식입니다. 아래의 4가지 단계를 거쳐서 자동으로 글이 생성됩니다.

  1. 여러 홈페이지에서 필요한 정보를 수집합니다.
  2. 수집한 정보를 기반으로 자동으로 글을 작성합니다.
  3. 수집한 정보를 기반으로 썸네일을 생성합니다. (오늘 다룰 내용)
  4. 작성된 글과 썸네일을 워드프레스 API를 이용해서 업로드 합니다.

 

워드프레스 자동 글 작성 방법

우선 워드프레스에 글을 자동으로 작성하는 방법에 대해서는 아래 글을 참고하시기 바랍니다.

2022.05.19 - [웹페이지 운영/워드프레스] - 워드프레스 API를 통한 자동 글쓰기 예제 (파이썬 버전)

 

워드프레스 API를 통한 자동 글쓰기 예제 (파이썬 버전)

블로그 자동화를 위해서는 네이버 블로그나 티스토리 블로그로는 한계가 있습니다. 하루에 발행할 수 있는 글의 개수에 제한이 있기 때문입니다. 그래서 GitHub Pages나 워드프레스로 블로그를 옮

worldclassproduct.tistory.com

 

썸네일 자동 생성 스크립트

저는 풀타임 C언어 개발자입니다. C언어를 가장 잘 하지만 C언어 외에 다양한 프로그래밍 언어들을 사용하고 있습니다. C로 구현하기 참 어려운 것들을 파이썬에서는 아주 쉽게 구현할 수 있습니다. 수십줄의 라인이면 썸네일을 자동 생성하는 파이썬 스크립트를 구현할 수 있습니다.

우선 제가 작성한 스크립트부터 공유드립니다. 아래의 버튼을 클릭하시면 제가 GitHub에 업데이트해둔 스크립트를 확인하실 수 있습니다.

파이썬 스크립트

 

혹은 wget 명령으로 한 방에 다운로드도 가능합니다.

$ wget https://raw.githubusercontent.com/boyinblue/blog_automation/main/thumbnail/make_thumb.py

 

스크립트 전체는 아래와 같으며 추후에 추가적으로 수정될 수 있습니다.

#!/usr/bin/env python3

from PIL import Image, ImageDraw, ImageFont
  
# create Image object
text1 = None
text2 = None
img_name = None

font = 'Nanum JangMiCe.ttf'

background = Image.open('default.jpg')
foreground = Image.open('logo.png')
 
#create the coloured overlays
colors = {
    'dark_blue':{'c':(27,53,81),'p_font':'rgb(255,255,255)','s_font':'rgb(255, 212, 55)'},
    'grey':{'c':(70,86,95),'p_font':'rgb(255,255,255)','s_font':'rgb(93,188,210)'},
    'light_blue':{'c':(93,188,210),'p_font':'rgb(27,53,81)','s_font':'rgb(255,255,255)'},
    'blue':{'c':(23,114,237),'p_font':'rgb(255,255,255)','s_font':'rgb(255, 255, 255)'},
    'orange':{'c':(242,174,100),'p_font':'rgb(0,0,0)','s_font':'rgb(0,0,0)'},
    'purple':{'c':(114,88,136),'p_font':'rgb(255,255,255)','s_font':'rgb(255, 212, 55)'},
#    'red':{'c':(255,0,0),'p_font':'rgb(0,0,0)','s_font':'rgb(0,0,0)'},
#    'yellow':{'c':(255,255,0),'p_font':'rgb(0,0,0)','s_font':'rgb(27,53,81)'},
    'yellow_green':{'c':(232,240,165),'p_font':'rgb(0,0,0)','s_font':'rgb(0,0,0)'},
#    'green':{'c':(65, 162, 77),'p_font':'rgb(217, 210, 192)','s_font':'rgb(0, 0, 0)'}
    }

import random
color = random.choice(list(colors.items()))[0]
 
def add_color(image,c,transparency):
    color = Image.new('RGB',image.size,c)
    mask = Image.new('RGBA',image.size,(0,0,0,transparency))
    return Image.composite(image,color,mask).convert('RGB')
 
def center_text(img,font,text1,text2,fill1,fill2):
    draw = ImageDraw.Draw(img)
    w,h = img.size
    t1_width, t1_height = draw.textsize(text1, font)
    if t1_width > ( w - 10 ):
        return None
    t2_width, t2_height = draw.textsize(text2, font)
    p1 = ((w-t1_width)/2,h // 3)
    p2 = ((w-t2_width)/2,h // 3 + h // 5)
    draw.text(p1, text1, fill=fill1, font=font)
    draw.text(p2, text2, fill=fill2, font=font)
    return img
 
def add_text(img,color,text1,text2,logo=False,font=font,font_size=75):
    draw = ImageDraw.Draw(img)
 
    p_font = color['p_font']
    s_font = color['s_font']
     
    # starting position of the message
    img_w, img_h = img.size
    height = img_h // 3

    if logo == False:
        while True:
            stFont = ImageFont.truetype(font,size=font_size)
            if not center_text(img,stFont,text1,text2,p_font,s_font):
                print("Adjust size :", font_size)
                font_size = font_size - 2
                continue
            else:
                break
    else:
        stFont = ImageFont.truetype(font,size=font_size)
        text1_offset = (img_w // 4, height)
        text2_offset = (img_w // 4, height + img_h // 5)
        draw.text(text1_offset, text1, fill=p_font, font=stFont)
        draw.text(text2_offset, text2, fill=s_font, font=stFont)
    return img
 
def add_logo(background,foreground):
    bg_w, bg_h = background.size
    img_w, img_h = foreground.size
    img_offset = (20, 20)
#    img_offset = (20, (bg_h - img_h) // 2)
    background.paste(foreground, img_offset, foreground)
    return background
 
def write_image(background,color,text1,text2,foreground=''):
    background = add_color(background,color['c'],25)
    if not foreground:
        add_text(background,color,text1,text2,font_size=40)
    else:
        add_text(background,color,text1,text2,font_size=40, logo=True)
        add_logo(background,foreground)
    return background

def print_usage():
    print("(Usage) {} -output=output.jpg -t1=title -t2=tags".format(sys.argv[0]))
    print("(Example) {} -output=output.jpg \"-t1=GitHub API 메뉴얼\" \"-t2=#GitHub #API\"".format(sys.argv[0]))
 
if __name__ == '__main__':
    import sys
    for i in range(1, len(sys.argv)):
        if '-output=' in sys.argv[i]:
            img_name = sys.argv[i][8:]
        elif '-t1=' in sys.argv[i]:
            text1 = sys.argv[i][4:]
        elif '-t2=' in sys.argv[i]:
            text2 = sys.argv[i][4:]

    import os
    if not os.path.isdir("tmp"):
        os.mkdir("tmp")

    if not text1:
        text1 = input("제목 :")
    
    if not text2:
        text2 = input("내용 :")

    if not img_name:
        img_name = "tmp/{}.jpg".format(text1.replace(' ', ''))
        print("Set output filename :", img_name)
            
#    background = write_image(background,colors[color],text1,text2,foreground=foreground)
    background = write_image(background,colors[color],text1,text2)
    add_logo(background, foreground)
    background.save(img_name) 
    print("OK")

 

스크립트에 대해서 간략하게 설명드립니다.

  • 썸네일 파일은 tmp 디렉토리 내에 생성이 됩니다.
  • -output=output.jpg 와 같은 옵션으로 썸네일이 저장될 파일명을 지정할 수 있습니다.
    • 만약 지정하지 않을 경우, 제목을 통해서 파일명을 생성합니다.
  • -t1=Text와 같은 옵션으로 제목을 지정할 수 있습니다.
    • 만약 지정하지 않을 경우, 표준 입력으로 받을 수 있습니다.
  • -t2=Text와 같은 옵션으로 설명을 지정할 수 있습니다.
    • 만약 지정하지 않을 경우, 표준 입력으로 받을 수 있습니다.
  • 배경화면 이미지가 필요하며, default.jpg 파일을 사용합니다. 언제든지 변경 가능합니다.
  • 로고는 왼쪽 상단에 찍히며 logo.png 파일을 사용합니다. 언제든지 변경 가능합니다.

 

이상으로 썸네일 이미지를 자동으로 생성하는 파이썬 스크립트에 대한 설명을 모두 마칩니다.