首页 > 编程语言 >个人网页-测试程序-网页成功与api交互但未显示好的图片

个人网页-测试程序-网页成功与api交互但未显示好的图片

时间:2024-05-02 22:22:44浏览次数:33  
标签:网页 import image 测试程序 api file error return data

python:

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

# Configure Flask application
app = Flask(__name__, template_folder='../templates')
app.config['UPLOAD_FOLDER'] = 'uploads/'  # Assuming there is an 'uploads' folder at the same level as 'web'
logging.basicConfig(level=logging.DEBUG)

def encode_image_to_base64(image_path):
    """Encode image file to base64 string."""
    with Image.open(image_path) as image:
        buffered = io.BytesIO()
        image.save(buffered, format="PNG")
        return base64.b64encode(buffered.getvalue()).decode('utf-8')

def call_api(image_data):
    """Call an external API to process the image data."""
    url = "http://127.0.0.1:7860/sdapi/v1/txt2img"  # Replace with your actual API URL
    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": [image_data],
        "steps": 30,
        "width": 1024,
        "height": 1024,
    }
    try:
        response = requests.post(url, json=data)
        response.raise_for_status()  # Raises an HTTPError for bad responses
        return response.json()
    except requests.exceptions.RequestException as e:
        logging.error(f"API call failed: {e}")
        return None

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

@app.route('/upload', methods=['POST'])
def upload_file():
    """Handle image upload and API interaction."""
    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
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)  # Save file to uploads folder
        image_data = encode_image_to_base64(file_path)
        api_result = call_api(image_data)
        if api_result is not None:
            return jsonify(api_result)
        else:
            return jsonify({'error': 'API call failed'}), 500

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

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 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 an 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="result"></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.json())
            .then(data => {
                const resultDiv = document.getElementById('result');
                if (data.error) {
                    resultDiv.innerHTML = `<p>Error: ${data.error}</p>`;
                } else {
                    // Assuming the API returns an image URL or image data directly
                    resultDiv.innerHTML = `<img src="data:image/png;base64,${data.image}" alt="Processed Image">`;
                    // If data is structured differently, adjust accordingly
                }
            })
            .catch(error => {
                document.getElementById('result').innerHTML = `<p>Error: ${error.message}</p>`;
            });
        });
    </script>
</body>
</html>

 

标签:网页,import,image,测试程序,api,file,error,return,data
From: https://www.cnblogs.com/zly324/p/18170650

相关文章

  • WPF CollectionViewSource ICollectionViewLiveShaping IsLiveSorting
    <Windowx:Class="WpfApp82.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.......
  • webapi创建和调用WebService
    首先需要引入soapcore包这个包提供了所需的类和soap终结点中间件。引入这个这个包之后,我们需要定义提供的服务。这里我写了一个用于查询省份面积的服务。省份信息服务///<summary>///省份信息服务接口///</summary>[ServiceContract]publicinterfaceIProvinceInfo......
  • 模拟微任务 判断是否有对应的api
    if(typeofPromise!=='undefined'&&isNative(Promise)){}functionrunMicrotask(func){if(typeofPromise==='function'){Promise.resolve().then(func)return}if(typeofMutationObserver==='functi......
  • Web Audio API
    WebAudioAPI:控制Web上的音频提供了一个功能强大的通用系统,允许开发人员选择音频源,为音频添加效果,创建音频可视化,应用空间效果(如平移)等等(oscillator)振荡器播放声音<buttontype="button"class="btn-play">play</button><script>//WebAudioAPI//创建一个Au......
  • 报错“Please indicate a valid Swagger or OpenAPI version field”
    报错“PleaseindicateavalidSwaggerorOpenAPIversionfield”报错信息PleaseindicateavalidSwaggerorOpenAPIversionfield.Supportedversionfieldsareswagger:"2.0"andthosethatmatchopenapi:3.0.n(forexample,openapi:3.0.0). 原因分析根......
  • 使用@lakehouse-rs/flight-sql-client nodejs api 快速访问dremio 服务
    @lakehouse-rs/flight-sql-client是基于rust开发的nodearrowflightsqlclient,dremio目前也是推荐基于arrowflightsql的访问模式参考代码package.json{"name":"node-arrow-flight-sql","version":"1.0.0","ma......
  • Audio Output Devices API
    AudioOutputDevicesAPI:音频输出设备API允许Web应用程序提示用户应使用什么输出设备进行音频播放。<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width,i......
  • Prioritized Task Scheduling API
    PrioritizedTaskSchedulingAPI一种标准化的方法来优先处理属于应用程序的所有任务,无论它们是在网站开发人员的代码中定义的,还是在第三方库和框架中定义的任务优先级是非常粗粒度的,并且基于任务是否阻止用户交互或以其他方式影响用户体验,或者可以在后台运行基于Promise的,......
  • Trusted Types API
    TrustedTypesAPI:锁定DOMAPI的不安全部分,以防止客户端跨站脚本(XSS)攻击untrusted<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width......
  • THUSC2024 & APIO2024 游记
    第二次联赛以上的比赛。Day-nlxs突然通知:从五月七日开始要去镇海中学集训......