lexicalspace commited on
Commit
118e0a8
·
verified ·
1 Parent(s): 364101e

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +39 -0
main.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, send_file
2
+ from flask_cors import CORS
3
+ from PIL import Image
4
+ import io
5
+
6
+ app = Flask(__name__)
7
+ CORS(app) # Allows the frontend to talk to this backend
8
+
9
+ @app.route('/optimize', methods=['POST'])
10
+ def optimize_image():
11
+ try:
12
+ # 1. Get the file
13
+ file = request.files['image']
14
+ quality = int(request.form.get('quality', 80))
15
+
16
+ # 2. Process in Memory (No saving to disk = No Crash)
17
+ img = Image.open(file)
18
+
19
+ # Convert to RGB if necessary (e.g., if PNG has transparency)
20
+ if img.mode in ("RGBA", "P"):
21
+ img = img.convert("RGB")
22
+
23
+ buffer = io.BytesIO()
24
+ # Save as WebP (High performance format)
25
+ img.save(buffer, 'WEBP', quality=quality, optimize=True)
26
+ buffer.seek(0)
27
+
28
+ # 3. Return the file
29
+ return send_file(
30
+ buffer,
31
+ mimetype='image/webp',
32
+ as_attachment=True,
33
+ download_name='optimized.webp'
34
+ )
35
+ except Exception as e:
36
+ return {"error": str(e)}, 500
37
+
38
+ if __name__ == '__main__':
39
+ app.run(debug=True, port=5000)