Install Flask and Pillow
pip install Flask Pillow
Project Structure
project/
├── app.py
└── templates/
└── index.html
app.py file code
from flask import Flask, render_template, request, send_file
from PIL import Image
import io
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
# ตรวจสอบว่าอัปโหลดไฟล์หรือไม่
if "image" not in request.files:
return "No file part"
file = request.files["image"]
if file.filename == "":
return "No selected file"
try:
# เปิดและปรับขนาดภาพ
img = Image.open(file)
new_size = (int(img.width * 0.5), int(img.height * 0.5))
img_resized = img.resize(new_size, Image.ANTIALIAS)
# บันทึกในหน่วยความจำแล้วส่งคืน
img_io = io.BytesIO()
img_resized.save(img_io, format="JPEG")
img_io.seek(0)
return send_file(img_io, mimetype="image/jpeg")
except Exception as e:
return f"Error: {str(e)}"
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
index.html file code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Resizer</title>
</head>
<body>
<h1>Upload an Image to Resize</h1>
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*">
<button type="submit">Resize Image</button>
</form>
</body>
</html>
Usage
- Open terminal in project folder and run
- python app.py
- Open browser and go to http://127.0.0.1:5000
- Upload image and see resized result