Posts
There's nothing here!
# app.py (Backend - Flask) from flask import Flask, render_template, request, send_file from PIL import Image import os import uuid app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads' app.config['CONVERTED_FOLDER'] = 'converted' app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp'} def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS'] def convert_image(filepath, output_format): img = Image.open(filepath) converted_filename = f"{uuid.uuid4()}.{output_format}" output_path = os.path.join(app.config['CONVERTED_FOLDER'], converted_filename) img.save(output_path, output_format.upper()) return output_path @app.route('/') def index(): return render_template('index.html') @app.route('/convert', methods=['POST']) def convert(): if 'file' not in request.files: return {'error': 'No file uploaded'}, 400 file = request.files['file'] output_format = request.form.get('format', 'png').lower() if file.filename == '': return {'error': 'No selected file'}, 400 if not allowed_file(file.filename): return {'error': 'Invalid file type'}, 400 if file and allowed_file(file.filename): filename = f"{uuid.uuid4()}.{file.filename.rsplit('.', 1)[1].lower()}" filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(filepath) try: converted_path = convert_image(filepath, output_format) return send_file(converted_path, as_attachment=True) except Exception as e: return {'error': str(e)}, 500 finally: # Clean up temporary files if os.path.exists(filepath): os.remove(filepath) if os.path.exists(converted_path): os.remove(converted_path) return {'error': 'Conversion failed'}, 500 if __name__ == '__main__': os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) os.makedirs(app.config['CONVERTED_FOLDER'], exist_ok=True) app.run(debug=True)
Skip to main content