Image Resizer In Kb

from PIL import Image import os UPLOAD_FOLDER = 'path/to/upload/folder' ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} def reduce_image_size(file_path, target_size): try: image = width, height = image.size aspect_ratio = width / height if width > target_size and aspect_ratio > 1: new_width = target_size new_height = int(target_size / aspect_ratio) elif height > target_size: new_height = target_size new_width = int(target_size * aspect_ratio) else: return file_path image = image.resize((new_width, new_height), Image.ANTIALIAS), optimize=True) return file_path except Exception as e: print(e) return file_path def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/reduce_image', methods=['POST']) def reduce_image(): file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file_path = os.path.join(UPLOAD_FOLDER, filename) reduced_image_path = reduce_image_size(file_path, 500) return send_file(reduced_image_path, as_attachment=True) else: return 'Invalid file type'

Post a Comment

Post a Comment (0)

Previous Post Next Post