ai網頁詳情頁-測試-只差樣式修改

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

HTML程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload and Display</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            display: flex;
            height: 100vh;
            background-color: #f4f4f4;
        }
        .container {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .left, .right {
            width: 50%;
        }
        .left {
            border-right: 2px solid #ccc;
        }
        img {
            max-width: 100%;
            margin-top: 20px;
        }
        form {
            width: 100%;
            max-width: 400px;
        }
        input, button {
            width: 100%;
            padding: 10px;
            margin-top: 10px;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
    <div class="container left">
        <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="uploadDisplay"></div> <!-- Div to display uploaded image -->
    </div>
    <div class="container right" id="imageDisplay">
        <!-- Processed images will be displayed here -->
    </div>

    <script>
        document.getElementById('uploadForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const formData = new FormData(this);
            const fileInput = document.querySelector('input[type="file"]');
            if(fileInput.files.length > 0) {
                const file = fileInput.files[0];
                const image = new Image();
                image.src = URL.createObjectURL(file);
                document.getElementById('uploadDisplay').innerHTML = '';
                document.getElementById('uploadDisplay').appendChild(image);
            }

            fetch('/upload', {
                method: 'POST',
                body: formData,
            })
            .then(response => response.blob())
            .then(blob => {
                if(blob.type.startsWith('image/')) {
                    const url = URL.createObjectURL(blob);
                    const processedImage = new Image();
                    processedImage.src = url;
                    const displayDiv = document.getElementById('imageDisplay');
                    displayDiv.innerHTML = '';  // Clear previous content
                    displayDiv.appendChild(processedImage);  // Display the processed 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>
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/'
app.config['PROCESSED_FOLDER'] = 'processed/'

def encode_image_to_base64(image):
    """Encode image to base64 string for API consumption."""
    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):
    """Decode base64 image string and save it to specified folder."""
    image_data = base64.b64decode(b64_image)
    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(image_data)
    return output_path

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

@app.route('/upload', methods=['POST'])
def upload_file():
    """Handle file upload and image processing."""
    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
        upload_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(upload_path)

        with Image.open(upload_path) as img:
            encoded_image = encode_image_to_base64(img)
            data = {
                "prompt": "<lora:CWG_archisketch_v1:1>,Building,pre sketch,masterpiece,best quality,featuring markers,(3D:0.7)",
                "negative_prompt": "blurry, lower quality, glossy finish,insufficient contrast",
                "init_images": [encoded_image],
                "steps": 30,
                "width": img.width,
                "height": img.height,
                "seed": random.randint(1, 10000000),
                "alwayson_scripts": {
                    "ControlNet": {
                        "args": [
                            {
                                "enabled": "true",
                                "pixel_perfect": "true",
                                "module": "canny",
                                "model": "control_v11p_sd15_canny_fp16 [b18e0966]",
                                "weight": 1,
                                "image": encoded_image
                            },
                            {
                                "enabled": "true",
                                "pixel_perfect": "true",
                                "module": "depth",
                                "model": "control_v11f1p_sd15_depth_fp16 [4b72d323]",
                                "weight": 1,
                                "image": encoded_image
                            }
                        ]
                    }
                }
            }

            api_url = 'http://127.0.0.1:7860/sdapi/v1/txt2img'  # Change to your actual API URL
            response = requests.post(api_url, json=data)
            if response.status_code == 200:
                processed_image_b64 = response.json().get('images')[0]
                save_path = save_decoded_image(processed_image_b64, app.config['PROCESSED_FOLDER'], "processed_image")
                return send_from_directory(app.config['PROCESSED_FOLDER'], os.path.basename(save_path))
            else:
                return jsonify({'error': 'Failed to get response from API'}), response.status_code

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

相關文章