GIF / app.py
yangtb24's picture
Create app.py
98ba7ad verified
raw
history blame
2.44 kB
import os
from flask import Flask, request, send_file
from io import BytesIO
from PIL import Image
from imageio import mimwrite
app = Flask(__name__)
HTML_CONTENT = """
<!DOCTYPE html>
<html>
<head>
<title>GIF Generator</title>
<style>
body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background-color: #f4f4f4; }
.container { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); text-align: center; }
input[type="file"] { margin-bottom: 10px; display: block; margin-left: auto; margin-right: auto; }
button { background-color: #007bff; color: white; padding: 10px 15px; border: none; border-radius: 5px; cursor: pointer; }
button:hover { background-color: #0056b3; }
#gif-container { margin-top: 20px; }
#gif-image { max-width: 100%; }
</style>
</head>
<body>
<div class="container">
<h1>GIF Generator</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="images" accept="image/*" multiple>
<button type="submit">Generate GIF</button>
</form>
</div>
</body>
</html>
"""
@app.route('/', methods=['GET'])
def index():
return HTML_CONTENT
@app.route('/upload', methods=['POST'])
def upload():
try:
files = request.files.getlist('images')
if not files:
return "No images uploaded", 400
images = []
for file in files:
if file:
try:
img = Image.open(BytesIO(file.read()))
images.append(img)
except Exception as e:
print(f"Error opening image: {e}")
return f"Error opening image: {e}", 500
if not images:
return "No valid images processed", 400
# Generate GIF using imageio
gif_bytes = BytesIO()
mimwrite(gif_bytes, [img for img in images], format='GIF', fps=10)
gif_bytes.seek(0)
return send_file(
gif_bytes,
mimetype='image/gif',
download_name='animated.gif'
)
except Exception as e:
print(f"Error during upload: {e}")
return f"Error: {e}", 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)), debug=True)