import os from flask import Flask, request, jsonify, render_template from io import BytesIO from PIL import Image from imageio import mimwrite import base64 app = Flask(__name__) HTML_CONTENT = """ GIF Generator

GIF Generator

""" @app.route('/', methods=['GET']) def index(): return HTML_CONTENT @app.route('/upload', methods=['POST']) def upload(): try: files = request.files.getlist('images') delay_ms = int(request.form.get('delay', 100)) if not files: return "No images uploaded", 400 images = [] max_width = 0 max_height = 0 for file in files: if file: try: img = Image.open(BytesIO(file.read())) max_width = max(max_width, img.width) max_height = max(max_height, img.height) 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 # Resize images to the largest dimensions resized_images = [] for img in images: resized_img = img.resize((max_width, max_height), Image.LANCZOS) resized_images.append(resized_img) # Generate GIF using imageio with loop and duration gif_bytes = BytesIO() mimwrite(gif_bytes, [img for img in resized_images], format='GIF', loop=0, duration=delay_ms/1000) gif_bytes.seek(0) gif_base64 = base64.b64encode(gif_bytes.read()).decode('utf-8') gif_url = f'data:image/gif;base64,{gif_base64}' return jsonify({'gif_url': gif_url}) 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)