from flask import Flask, request, jsonify from flask_cors import CORS from PIL import Image import requests import io app = Flask(__name__) CORS(app) @app.route('/') def root(): return 'ok' @app.route('/api/bitmap', methods=['POST']) def bitmap(): if 'file' not in request.files: return jsonify({"error": "no file"}), 400 file = request.files['file'] if file.filename == '': return jsonify({"error": "no file"}), 400 if not file.filename.lower().endswith('.png'): return jsonify({"error": "invalid file format"}), 400 try: image_stream = io.BytesIO(file.read()) img = Image.open(image_stream) img.save('test.png') print(img.tobytes()) # 1. 確保尺寸符合你的硬體需求 (296x152) # 如果你的圖片不是這個尺寸,建議先 resize img = img.resize((296, 152)).convert('1').transpose(Image.Transpose.ROTATE_90).transpose(Image.Transpose.FLIP_LEFT_RIGHT) # 2. 直接獲取二進制數據 (Bit-packed) # Pillow '1' 模式的 tobytes() 會將 8 個像素縮成 1 個 byte raw_bits = img.tobytes() # 3. 組合 PBM P4 標頭與數據 header = f'P4\n152 296\n'.encode('ascii') payload = header + raw_bits print(raw_bits) # 測試寫入檔案 (必須用 'wb' 模式) with open('test.pbm', mode='wb') as f: f.write(payload) # 4. 發送請求 req = requests.put('http://172.16.0.130/api/tag', data=payload, headers={'Content-Type': 'image/x-portable-bitmap'}) return jsonify({'message': 'success', 'bytes_sent': len(payload)}) except Exception as e: return jsonify({"error": str(e)}), 500 if __name__ == '__main__': app.run('0.0.0.0', port=80, debug=1)