Hướng dẫn send base64 image to server python - gửi hình ảnh base64 tới máy chủ python

lựa chọn 1

Như đã đề cập trước đây ở đây, cũng như ở đây và ở đây, người ta nên sử dụng UploadFile, để tải lên các tệp từ các ứng dụng khách (để đọc/ghi async hãy xem câu trả lời này). Ví dụ:

Phía máy chủ:

@app.post("/upload")
def upload(file: UploadFile = File(...)):
    try:
        contents = file.file.read()
        with open(file.filename, 'wb') as f:
            f.write(contents)
    except Exception:
        return {"message": "There was an error uploading the file"}
    finally:
        file.file.close()
        
    return {"message": f"Successfuly uploaded {file.filename}"}

phía khách hàng:

import requests

url = 'http://127.0.0.1:8000/upload'
file = {'file': open('images/1.png', 'rb')}
resp = requests.post(url=url, files=file) 
print(resp.json())

Lựa chọn 2

Tuy nhiên, nếu bạn vẫn cần gửi hình ảnh được mã hóa

import requests

url = 'http://127.0.0.1:8000/upload'
file = {'file': open('images/1.png', 'rb')}
resp = requests.post(url=url, files=file) 
print(resp.json())
0, bạn có thể làm điều đó như được mô tả trước đây ở đây (tùy chọn 2). Về phía máy khách, bạn có thể mã hóa hình ảnh thành
import requests

url = 'http://127.0.0.1:8000/upload'
file = {'file': open('images/1.png', 'rb')}
resp = requests.post(url=url, files=file) 
print(resp.json())
0 và gửi nó bằng yêu cầu
import requests

url = 'http://127.0.0.1:8000/upload'
file = {'file': open('images/1.png', 'rb')}
resp = requests.post(url=url, files=file) 
print(resp.json())
2 như sau:

phía khách hàng:

import base64
import requests

url = 'http://127.0.0.1:8000/upload'
with open("photo.png", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
    
payload ={"filename": "photo.png", "filedata": encoded_string}
resp = requests.post(url=url, data=payload) 

Lựa chọn 2

Phía máy chủ:

@app.post("/upload")
def upload(filename: str = Form(...), filedata: str = Form(...)):
    image_as_bytes = str.encode(filedata)  # convert string to bytes
    img_recovered = base64.b64decode(image_as_bytes)  # decode base64string
    try:
        with open("uploaded_" + filename, "wb") as f:
            f.write(img_recovered)
    except Exception:
        return {"message": "There was an error uploading the file"}
        
    return {"message": f"Successfuly uploaded {filename}"} 

lựa chọn 1

Như đã đề cập trước đây ở đây, ở đây và ở đây, người ta nên sử dụng UploadFile, để tải lên các tệp từ các ứng dụng khách. Ví dụ:

Phía máy chủ:

@app.post("/upload")
async def upload(file: UploadFile = File(...)):
    try:
        contents = await file.read()
        with open(file.filename, 'wb') as f:
            f.write(contents)
    except Exception:
        return {"message": "There was an error uploading the file"}
    finally:
        await file.close()
        
    return {"message": f"Successfuly uploaded {file.filename}"}

phía khách hàng:

import requests

url = 'http://127.0.0.1:8000/upload'
file = {'file': open('images/1.png', 'rb')}
resp = requests.post(url=url, files=file) 
print(resp.json())

Lựa chọn 2

Tuy nhiên, nếu bạn vẫn cần gửi hình ảnh được mã hóa

import requests

url = 'http://127.0.0.1:8000/upload'
file = {'file': open('images/1.png', 'rb')}
resp = requests.post(url=url, files=file) 
print(resp.json())
0, bạn có thể làm điều đó như được mô tả trước đây ở đây (tùy chọn 2). Về phía máy khách, bạn có thể mã hóa hình ảnh thành
import requests

url = 'http://127.0.0.1:8000/upload'
file = {'file': open('images/1.png', 'rb')}
resp = requests.post(url=url, files=file) 
print(resp.json())
0 và gửi nó bằng yêu cầu
import requests

url = 'http://127.0.0.1:8000/upload'
file = {'file': open('images/1.png', 'rb')}
resp = requests.post(url=url, files=file) 
print(resp.json())
2 như sau:

phía khách hàng:

import base64
import requests

url = 'http://127.0.0.1:8000/upload'
with open("photo.png", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
    
payload ={"filename": "photo.png", "filedata": encoded_string}
resp = requests.post(url=url, data=payload) 

Lựa chọn 2

Phía máy chủ:

@app.post("/upload")
async def upload(filename: str = Form(...), filedata: str = Form(...)):
    image_as_bytes = str.encode(filedata)  # convert string to bytes
    img_recovered = base64.b64decode(image_as_bytes)  # decode base64string
    try:
        with open("uploaded_" + filename, "wb") as f:
            f.write(img_recovered)
    except Exception:
        return {"message": "There was an error uploading the file"}
        
    return {"message": f"Successfuly uploaded {filename}"} 

socket.on ('data', function (data) {// nghe trên máy khách phát ra 'dữ liệu'

Tệp này chứa văn bản unicode hai chiều có thể được giải thích hoặc biên dịch khác với những gì xuất hiện dưới đây.Để xem xét, hãy mở tệp trong một trình soạn thảo cho thấy các ký tự Unicode ẩn.Tìm hiểu thêm về các ký tự unicode hai chiều

importcv2 cv2
Nhập khẩu#Python-Socketio của @MiguelGrinberg socketio #python-socketio by @miguelgrinberg
importbase64 base64
Sio = socketio.client () = socketio.Client()
Sio.connect ('http: //x.x.x.x: xxxx).connect('http://x.x.x.x:xxxx)
cam = cv2.videocapture (0) = cv2.VideoCapture(0)
while (đúng): (True):
ret, frame = cam.Read () # Nhận khung từ webcam, frame = cam.read() # get frame from webcam
res, frame = cv2.imencode ('. jpg', frame) # từ hình ảnh đến bộ đệm nhị phân, frame = cv2.imencode('.jpg', frame) # from image to binary buffer
data = base64.b64encode (khung) # chuyển đổi sang định dạng base64 = base64.b64encode(frame) # convert to base64 format
Sio.Emit ('Dữ liệu', dữ liệu) # Gửi đến máy chủ.emit('data', data) # send to server
Cam.Release ().release()

Tệp này chứa văn bản unicode hai chiều có thể được giải thích hoặc biên dịch khác với những gì xuất hiện dưới đây.Để xem xét, hãy mở tệp trong một trình soạn thảo cho thấy các ký tự Unicode ẩn.Tìm hiểu thêm về các ký tự unicode hai chiều

varapp=require('express')(); app = require('express')();
varhttp=require('http').createServer(app); http = require('http').createServer(app);
vario=require('socket.io')(http); io = require('socket.io')(http);
varsizeof=require('object-sizeof'); sizeof = require('object-sizeof');
app.get('/',function(req,res){.get('/', function (req, res) {
res.send('running');.send('running');
}))
io.on('connection',function(socket){.on('connection', function (socket) {
socket.on ('data', function (data) {// nghe trên máy khách phát ra 'dữ liệu'.on('data', function (data) { // listen on client emit 'data'
varret=Object.assign({},data,{ ret = Object.assign({}, data, {
Khung: Buffer.From (Data.Frame, 'Base64').: Buffer.from(data.frame, 'base64').toString() // from buffer to base64 string
}))
socket.on ('data', function (data) {// nghe trên máy khách phát ra 'dữ liệu'.emit('data', ret); // emmit to socket
}))
}))
http.listen(3000,function(){.listen(3000, function () {
socket.on ('data', function (data) {// nghe trên máy khách phát ra 'dữ liệu'.log('listening on *:3333');
}))