Pythonでブラウザから画像データを受け取る
ブラウザでローカルに保存している画像を選択し、それをPythonに渡す。Python側でOpenCVで画像処理をする、という想定。今日のところは画像を保存するところまで。画像はドキュメントルートに保存される。
コードの解説(忘備録)は後日、新しい記事としてポストする。
プログラム
Python3.8.1
# coding: utf-8 import cgi import sys import io import base64 import cv2 import numpy as np sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding = 'utf-8') #printで出力する内容をutf-8にする print('Content-Type: text/html; charset=UTF-8\n') #ファイルの種類を定義 #ブラウザに表示する内容を記述 ## HTMLを変数html_bodyに代入している html_body = """ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Python CGI Image</title> </head> <body> <form action="14_cgi_image_001.py" method="post" enctype="multipart/form-data"> <input type="file" name="imagefile"> <input type="submit" value="保存する"> </form> </body> </html>""" form = cgi.FieldStorage() img = form.getvalue("imagefile") try: # after_encode = base64.b64encode(img) # after_encode = str(after_encode) # after_encode = after_encode.replace("b'","") # after_encode = after_encode.replace("'","") # print("<img src='data:image/jpeg;base64,{0}'>".format(after_encode)) arr = np.asarray(bytearray(img), dtype=np.uint8) d_img = cv2.imdecode(arr, -1) cv2.imwrite('Converted.jpg', d_img) print("保存しました") except: print(html_body)
[14_cgi_image_001.py]