首页 > 其他分享 >ai网页详情页-测试-api调用成功返图!

ai网页详情页-测试-api调用成功返图!

时间:2024-05-03 16:34:47浏览次数:25  
标签:返图 网页 image response 详情页 file path os app

"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>

 

标签:返图,网页,image,response,详情页,file,path,os,app
From: https://www.cnblogs.com/zly324/p/18171324

相关文章

  • 个人网页-测试程序-网页成功与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......
  • python 实现网页 pdf 转 docx
    1、安装python库pip3installflaskPyPDF2python-docx2、创建一个Flask应用,并编写处理文件上传和转换的代码vimpdf_to_docx.pyimportosfromflaskimportFlask,render_template,request,send_filefromPyPDF2importPdfReaderfromioimportBytesIOfromdocx......
  • 【性能监控】如何有效监测网页静态资源大小?
    前言作为前端人员肯定经常遇到这样的场景:需求刚上线,产品拿着手机来找你,为什么页面打开这么慢呀,心想自己开发的时候也有注意性能问题呀,不可能会这么夸张。那没办法只能排查下是哪一块影响了页面的整体性能,打开浏览器控制台一看,页面上的这些配图每张都非常大,心想这些配图都这么大,页......