Pillow으로 원하는 사이즈로 이미지 만들기(with Flask)

원하는 사이즈의 목업이미지(?)를 만들어는 기능?이 필요했다.

http(s)://Address/{가로}x{세로}” 형식으로 호출하면 아래와 같이 JPG 이미지를 웹으로 출력해주는 형식이다. ex) http(s)://Address/100×100

https(s):/Address/300×200
https(s):/Address/200×200

급하게 만들어서 예외 처리 따위는 되어 있지 않은 코드이지만, 기록해보기로 했다.

import flask
import io
from PIL import Image, ImageDraw, ImageFont

app = flask.current_app


@app.route('/<size>')
def mockup(size):
    # URL로 입력된 사이즈 정보를 소문자로 변경
    size = size.lower()

    if 'x' in size:
        if size.count('x') != 1:
            return create_image()
        elif size.count('x') > 1:
            w = int(size)
            return create_image(w)
        else:
            w, h = int(size.split('x')[0]), int(size.split('x')[1])
            return create_image(w, h)


def create_image(w=200, h=None):
    image_color = 'gray'
    drawline_color = 'white'
    # 높이가 없으면 세로와 같은 크기로 선언
    if h is None:
        h = w
    # 목업 기본 이미지 생성
    box = Image.new(
        mode='RGB',
        size=(int(w), int(h)),
        color=image_color
    )
    draw = ImageDraw.Draw(box)
    # 바운딩 박스, 라인 의 시작점
    margin = min(int(w/10), int(h/10)])
    # 바운딩 박스 그리기
    draw.rectangle(
        (
            # x 시작 좌표
            int(margin),
            # y 시작 좌표
            int(margin),
            # x 끝 좌표
            int(w - margin),
            # y 끝 좌표
            int(h - margin)
        ), outline = drawline_color,
        width = 1
    )
    # \ 표시를 위한 대각선 그리기
    draw.line(
        (
            # x 시작 좌표
            int(margin),
            # y 시작 좌표
            int(margin),
            # x 끝 좌표
            int(w - margin),
            # b 끝 좌표
            int(h - margin)
        ),
        fill = drawline_color, width = 1
    )
    # / 표시를 위한 대각선 그리기
    draw.line(
        (
            # x 시작 좌표
            int(w - margin),
            # y 시작 좌표
            int(margin),
            # x 끝 좌표
            int(margin),
            # y 끝 좌표
            int(h - margin)
        ),
    fill = drawline_color, width = 1
    )
    # 생성한 이미지를 메모리
    byteio = io.BytesIO()
    box.save(byteio, format='JPEGE', optimize=True, qualty=95)
    boxRes = byteio.getvalue()
    byteio.close()
    return flask.Response(boxRes, mimetype='image/jpg')

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다