ai網頁詳情頁-測試-api呼叫成功返圖!

不上火星不改名發表於2024-05-03

"C:\Users\wujie1\Desktop\程式測試\templates\upload.html"

"C:\Users\wujie1\Desktop\程式測試\python.py"

C:\Users\wujie1\Desktop\程式測試\uploads

python

from flask import Flask, render_template, request, jsonify, send_from_directory
import os
import requests
import base64
from PIL import Image
import io
import random

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'


def encode_image_to_base64(image):
    buffered = io.BytesIO()
    image.save(buffered, format="PNG")
    return base64.b64encode(buffered.getvalue()).decode('utf-8')


def save_decoded_image(b64_image, folder_path, image_name):
    seq = 0
    output_path = os.path.join(folder_path, f"{image_name}.png")
    while os.path.exists(output_path):
        seq += 1
        output_path = os.path.join(folder_path, f"{image_name}({seq}).png")
    with open(output_path, 'wb') as image_file:
        image_file.write(base64.b64decode(b64_image))
    return output_path


@app.route('/', methods=['GET'])
def index():
    return render_template('upload.html')


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    if file:
        filename = file.filename
        image_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(image_path)

        with Image.open(image_path) as img:
            encoded_image = encode_image_to_base64(img)

        data = {
            "prompt": "<prompt_text>",
            "init_images": [encoded_image],
            "steps": 30,
            "width": img.width,
            "height": img.height,
            "seed": random.randint(1, 10000000)
        }

        response = requests.post('http://127.0.0.1:7860/sdapi/v1/txt2img', json=data)
        if response.status_code == 200:
            response_json = response.json()
            saved_image_path = save_decoded_image(response_json['images'][0], app.config['UPLOAD_FOLDER'],
                                                  "processed_image")
            return send_from_directory(app.config['UPLOAD_FOLDER'], os.path.basename(saved_image_path))
        else:
            return jsonify({'error': 'Failed to get response from API'}), 500


if __name__ == '__main__':
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    app.run(debug=True, port=5000)

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Image and Process</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        img {
            max-width: 100%;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Upload Image</h1>
        <form id="uploadForm" enctype="multipart/form-data">
            <input type="file" name="file" required>
            <button type="submit">Upload and Process</button>
        </form>
        <div id="imageDisplay"></div>
    </div>

    <script>
        document.getElementById('uploadForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const formData = new FormData(this);
            fetch('/upload', {
                method: 'POST',
                body: formData,
            })
            .then(response => response.blob())
            .then(blob => {
                if(blob.type.startsWith('image/')) {
                    const url = URL.createObjectURL(blob);
                    const image = new Image();
                    image.src = url;
                    document.getElementById('imageDisplay').innerHTML = '';
                    document.getElementById('imageDisplay').appendChild(image);
                } else {
                    document.getElementById('imageDisplay').textContent = 'Failed to process image.';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('imageDisplay').textContent = 'Error uploading and processing image.';
            });
        });
    </script>
</body>
</html>

相關文章