首页 > 其他分享 >ai网页详情页-测试-只差样式修改

ai网页详情页-测试-只差样式修改

时间:2024-05-03 18:22:34浏览次数:11  
标签:网页 image 只差 详情页 file path FOLDER os app

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)

 

标签:网页,image,只差,详情页,file,path,FOLDER,os,app
From: https://www.cnblogs.com/zly324/p/18171465

相关文章

  • ai网页详情页-测试-api调用成功返图+左侧界面及时显示
    PYTHONfromflaskimportFlask,render_template,request,jsonify,send_from_directoryimportosimportrequestsimportbase64fromPILimportImageimportioimportrandomapp=Flask(__name__)app.config['UPLOAD_FOLDER']='uploads/......
  • ai网页详情页-测试-api调用成功返图!
    "C:\Users\wujie1\Desktop\程序测试\templates\upload.html""C:\Users\wujie1\Desktop\程序测试\python.py"C:\Users\wujie1\Desktop\程序测试\uploads pythonfromflaskimportFlask,render_template,request,jsonify,send_from_director......
  • 个人网页-测试程序-网页成功与api交互但未显示好的图片
    python:fromflaskimportFlask,render_template,request,jsonifyimportrequestsimportbase64importosfromPILimportImageimportioimportlogging#ConfigureFlaskapplicationapp=Flask(__name__,template_folder='../templates')app.c......
  • BurpSuite连接浏览器代理无法打开部分网页问题
    本人写这篇记录时,尚未熟悉bp基本操作,仅记录该次探索bp功能解决问题的心路历程。发现并解决问题最近两天为能打开尘封已久的bp,抓包做题,卸载了jdk20,下了jdk1.8(高版本jdk破解用的java命令完全不能执行,挣扎了一天尝试找功能相同的jdk20代码,以失败告终),一顿操作后发现居然有的页面还是......
  • 引爆你的网页乐趣!前端十个令人捧腹的JavaScript整蛊代码。
    愚人节整蛊代码。想要在网页上增添一抹幽默与惊喜吗?或是想给你的朋友一个意想不到的“小惊喜”?那么,这十款简单而有趣的JavaScript前端整蛊代码绝对能满足你的需求!每一个代码都能让你的网页瞬间变得生动有趣。1,抖动页面在线效果演示:张苹果博客模拟页面抖动的动画效果。3秒后......
  • 网页布局------导航栏悬浮特效
    实现效果:当鼠标指针悬浮在导航栏上会出现内阴影效果页面结构<ul><li>首页</li><li>知识星球</li><li>趣味问答</li><li>奖品</li></ul>页面样式*{margin:0;padding:0;......
  • js设置网页标题、关键字、描述
    import.meta.env.VITE...Vue.js3.x获取环境变量letdocTitle=import.meta.env.VITE_TITLE;letdocDesc=import.meta.env.VITE_DESCRIPT;letdocKeywords=import.meta.env.VITE_KEYWORDS;//设置页面标题document.title=docTitle;//设置页......
  • 网页布局------几种布局方式
    1、认识布局(1)确认页面的版心宽度版心是指页面的有效使用面积,主要元素以及内容所在的区域,一般在浏览器窗口中水平居中显示。在设计网页时,页面尺寸宽度一般为1200-1920排序。但是为例适配不同分辨率的显示器,一般版心宽度为1000-1200px。例如,屏幕分辨率为1021*768的浏览器,在浏览器......
  • 在线版CAD二次开发修改UI配置的方法(纯国产内核网页CAD)
    前言我们根据mxcad开发包开发了一个完整的在线CAD应用,它包括了绘图、编辑、文字样式设置、图层设置、线型设置等功能的实现。我们同时提供了一个插件的开发接口,用户可以在该接口的基础上进行二次开发,这样就能够为用户减少从头开发的工作量,可以快速将一个完整的CAD项目集成到用......
  • 网页退出全屏和全屏显示
    <div@click="fullScreen">全屏显示</div><div@click="exitFullScreen">退出全屏</div>fullScreen(){varde=document.documentElement;if(de.requestFullscreen){de.requestFull......