Flask?web上傳獲取圖像Image讀取并使用方式
Flask web上傳獲取圖像Image讀取并使用
圖片上傳界面
后端
@app.route('/upload')
def upload_test():
return render_template('new.html')前端:new.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<form method="post" action="http://localhost:6600/up_photo" enctype="multipart/form-data">
<input type="file" size="30" name="photo"/>
<br>
<!-- <input type="text" class="txt_input" name="name" style="margin-top:15px;"/>-->
<input type="submit" value="提交信息" class="button-new" style="margin-top:15px;"/>
</form>
</div>
</body>
</html>
圖片上傳后端處理代碼
后端
***stream獲取圖像文件,另外[‘photo’]與前端name="photo"屬性對(duì)其
@app.route('/up_photo', methods=['post'])
def up_photo():
img1 = request.files['photo']
print(type(img1))
img = Image.open(img1.stream)
# 保存圖片
img1.save(file_path)Flask上傳本地圖片并在頁(yè)面上顯示
使用Flask遠(yuǎn)程上傳圖片到服務(wù)器,并把獲取到的圖片顯示到前端頁(yè)面上。
方法一
目錄結(jié)構(gòu):

- '
static/images' 文件夾用來(lái)存放上傳過(guò)來(lái)的圖片 - '
templates’文件夾下的兩個(gè)html文件定義顯示頁(yè)面 upload_pictures.py是工程代碼
'static/images' 文件夾用來(lái)存放上傳過(guò)來(lái)的圖片‘templates’文件夾下的兩個(gè)html文件定義顯示頁(yè)面upload_pictures.py 是工程代碼
upload_pictures.py 代碼:
# coding:utf-8
from flask import Flask, render_template, request, redirect, url_for, make_response,jsonify
from werkzeug.utils import secure_filename
import os
import cv2
import time
from datetime import timedelta
#設(shè)置允許的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
app = Flask(__name__)
# 設(shè)置靜態(tài)文件緩存過(guò)期時(shí)間
app.send_file_max_age_default = timedelta(seconds=1)
# @app.route('/upload', methods=['POST', 'GET'])
@app.route('/upload', methods=['POST', 'GET']) # 添加路由
def upload():
if request.method == 'POST':
f = request.files['file']
if not (f and allowed_file(f.filename)):
return jsonify({"error": 1001, "msg": "請(qǐng)檢查上傳的圖片類型,僅限于png、PNG、jpg、JPG、bmp"})
user_input = request.form.get("name")
basepath = os.path.dirname(__file__) # 當(dāng)前文件所在路徑
upload_path = os.path.join(basepath, 'static/images', secure_filename(f.filename)) # 注意:沒(méi)有的文件夾一定要先創(chuàng)建,不然會(huì)提示沒(méi)有該路徑
# upload_path = os.path.join(basepath, 'static/images','test.jpg') #注意:沒(méi)有的文件夾一定要先創(chuàng)建,不然會(huì)提示沒(méi)有該路徑
f.save(upload_path)
# 使用Opencv轉(zhuǎn)換一下圖片格式和名稱
img = cv2.imread(upload_path)
cv2.imwrite(os.path.join(basepath, 'static/images', 'test.jpg'), img)
return render_template('upload_ok.html',userinput=user_input,val1=time.time())
return render_template('upload.html')
if __name__ == '__main__':
# app.debug = True
app.run(host='0.0.0.0', port=8987, debug=True)upload.html 文件代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask上傳圖片演示</title>
</head>
<body>
<h1>使用Flask上傳本地圖片并顯示示例一</h1>
<form action="" enctype='multipart/form-data' method='POST'>
<input type="file" name="file" style="margin-top:20px;"/>
<br>
<i>請(qǐng)輸入你當(dāng)前的心情(開心、超開心、超超開心):</i>
<input type="text" class="txt_input" name="name" value="超超開心" style="margin-top:10px;"/>
<input type="submit" value="上傳" class="button-new" style="margin-top:15px;"/>
</form>
</body>
</html>upload_ok.html文件代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask上傳圖片演示</title>
</head>
<body>
<h1>使用Flask上傳本地圖片并顯示示例一</h1>
<form action="" enctype='multipart/form-data' method='POST'>
<input type="file" name="file" style="margin-top:20px;"/>
<br>
<i>請(qǐng)輸入你當(dāng)前的心情(開心、超開心、超超開心):</i>
<input type="text" class="txt_input" name="name" value="超超開心" style="margin-top:10px;"/>
<input type="submit" value="上傳" class="button-new" style="margin-top:15px;"/>
</form>
<h1>閣下的心情是:{{userinput}}!</h1>
<img src="{{ url_for('static', filename= './images/test.jpg',_t=val1) }}" width="400" height="400" alt="你的圖片被外星人劫持了~~"/>
</body>
</html>直接運(yùn)行 python upload_pictures.py 就行了,定義了端口號(hào)8987,在本機(jī)上訪問(wèn) '127.0.0.1:8987/upload' ,出現(xiàn)以下界面:

點(diǎn)擊'瀏覽' 并上傳后,上傳的圖片保存到了 ‘static/images'目錄下,顯示結(jié)果:

方法二
目錄結(jié)構(gòu):

目錄文件介紹同方法一。
upload_pictures.py 代碼:
# coding:utf-8
from flask import Flask,render_template,request,redirect,url_for,make_response,jsonify
from werkzeug.utils import secure_filename
import os
import cv2
from datetime import timedelta
#設(shè)置允許的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
app = Flask(__name__)
# 設(shè)置靜態(tài)文件緩存過(guò)期時(shí)間
app.send_file_max_age_default = timedelta(seconds=1)
@app.route('/upload', methods=['POST', 'GET']) # 添加路由
def upload():
if request.method == 'POST':
f = request.files['file']
if not (f and allowed_file(f.filename)):
return jsonify({"error": 1001, "msg": "請(qǐng)檢查上傳的圖片類型,僅限于png、PNG、jpg、JPG、bmp"})
user_input = request.form.get("name")
basepath = os.path.dirname(__file__) # 當(dāng)前文件所在路徑
upload_path = os.path.join(basepath, 'static/images',secure_filename(f.filename)) #注意:沒(méi)有的文件夾一定要先創(chuàng)建,不然會(huì)提示沒(méi)有該路徑
f.save(upload_path)
image_data = open(upload_path, "rb").read()
response = make_response(image_data)
response.headers['Content-Type'] = 'image/png'
return response
return render_template('upload.html')
if __name__ == '__main__':
# app.debug = True
app.run(host = '0.0.0.0',port = 8987,debug= True)upload.html 文件代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask上傳圖片演示</title>
</head>
<body>
<h1>使用Flask上傳本地圖片并顯示示例二</h1>
<form action="" enctype='multipart/form-data' method='POST'>
<input type="file" name="file" style="margin-top:20px;"/>
<br>
<i>請(qǐng)輸入你當(dāng)前的心情(開心、超開心、超超開心):</i>
<input type="text" class="txt_input" name="name" value="超超開心" style="margin-top:10px;"/>
<input type="submit" value="上傳" class="button-new" style="margin-top:15px;"/>
</form>
</body>
</html>運(yùn)行 python upload_pictures.py ,端口號(hào)定義的是8987,在本機(jī)上訪問(wèn) '127.0.0.1:8987/upload' ,出現(xiàn)以下界面:

點(diǎn)擊'瀏覽' 并上傳后,上傳的圖片保存到了 ‘static/images'目錄下,顯示結(jié)果:

方法二顯示出來(lái)的圖片覆蓋了整個(gè)頁(yè)面。
tips: 如果是在其他機(jī)器上訪問(wèn),把127.0.0.1的IP換成服務(wù)器的IP就行了。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
七個(gè)非常實(shí)用的Python工具包總結(jié)
Python 擁有海量的包,無(wú)論是普通任務(wù)還是復(fù)雜任務(wù),我們經(jīng)常在應(yīng)用程序中使用大量的工具包.本文我將討論一些常被低估的數(shù)據(jù)科學(xué)包,包括:數(shù)據(jù)清理、應(yīng)用程序開發(fā)和調(diào)試方面,需要的朋友可以參考下2021-06-06
基于循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的古詩(shī)生成器
這篇文章主要為大家詳細(xì)介紹了基于循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的古詩(shī)生成器,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03
Django實(shí)現(xiàn)簡(jiǎn)單登錄的示例代碼
本文主要介紹了Django實(shí)現(xiàn)簡(jiǎn)單登錄的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
python使用wmi模塊獲取windows下的系統(tǒng)信息 監(jiān)控系統(tǒng)
Python用WMI模塊獲取Windows系統(tǒng)的硬件信息:硬盤分區(qū)、使用情況,內(nèi)存大小,CPU型號(hào),當(dāng)前運(yùn)行的進(jìn)程,自啟動(dòng)程序及位置,系統(tǒng)的版本等信息。2015-10-10
python解決js文件utf-8編碼亂碼問(wèn)題(推薦)
這篇文章主要介紹了python解決js文件utf-8編碼亂碼問(wèn)題,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2018-05-05
Python 中多態(tài)性的示例和類的繼承多態(tài)性詳解
多態(tài)性通常在類的方法中使用,其中我們可以具有相同方法名稱的多個(gè)類,本文給大家介紹Python 中多態(tài)性的示例和類的繼承多態(tài)性詳解,需要的朋友可以參考下2023-10-10
Django Admin設(shè)置應(yīng)用程序及模型順序方法詳解
這篇文章主要介紹了Django Admin設(shè)置應(yīng)用程序及模型順序方法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04

