본문 바로가기

PY(Python Image Processing)

파이썬 웹앱 버튼, 이미지 그리기 (python flask web-app create button, image draw)

728x90

[directory]

flask_image_app/

├── app.py
├── requirements.txt
└── templates/
    └── index.html

 

[requirement.txt]

Flask==2.3.2
Pillow==9.4.0

 

 

[app.py]

from flask import Flask, render_template, jsonify
import io
import base64
from PIL import Image, ImageDraw

app = Flask(__name__)

def generate_image():
    # 새로운 이미지 생성
    img = Image.new('RGB', (200, 200), color=(73, 109, 137))
    d = ImageDraw.Draw(img)
    # 노란색 사각형을 그리기
    d.rectangle([50, 50, 150, 150], fill=(255, 255, 0), outline=(255, 255, 0))

    # 메모리 버퍼에 이미지 저장
    buf = io.BytesIO()
    img.save(buf, format='PNG')
    buf.seek(0)  # 버퍼의 시작 위치로 이동
   
    # 이미지를 base64로 인코딩
    img_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
   
    return img_base64

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/generate_image', methods=['GET'])
def generate_image_route():
    img_base64 = generate_image()
    # JSON 응답으로 base64 인코딩된 이미지 전송
    return jsonify({'image_data': img_base64})

if __name__ == '__main__':
    app.run(debug=True)

 

 

[index.html]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Generator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f0f0f0;
            margin: 0;
        }
        #generate-btn {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-bottom: 20px;
        }
        #generate-btn:hover {
            background-color: #45a049;
        }
        #image-container img {
            max-width: 100%;
            height: auto;
            display: block;
        }
    </style>
</head>
<body>
    <button id="generate-btn" onclick="generateImage()">Generate Image</button>
    <div id="image-container"></div>

    <script>
        function generateImage() {
            fetch('/generate_image')
                .then(response => response.json())
                .then(data => {
                    const imageContainer = document.getElementById('image-container');
                    const img = document.createElement('img');
                    img.src = 'data:image/png;base64,' + data.image_data;
                    imageContainer.innerHTML = ''; // 기존 이미지 제거
                    imageContainer.appendChild(img);
                });
        }
    </script>
</body>
</html>

 

[operation]

pip install -r requirement.txt

python app.py

 

[check web browser]

http://127.0.0.1:5000

728x90