To create a Flask server endpoint that accepts PNG and JPEG image files and converts them to Base64 encoding, you can follow these steps:
-
Set Up Your Flask Application: Import the necessary modules and initialize your Flask app.
-
Create an Endpoint: Define a route that accepts POST requests with image files.
-
Handle File Uploads: Retrieve the uploaded files from the request.
-
Validate the Files: Check if the files are of allowed image types (PNG or JPEG).
-
Convert Images to Base64: Read the file content and encode it using Base64.
-
Return the Base64 String: Send the Base64-encoded string back in the response.
Below is a complete example demonstrating how to achieve this:
from flask import Flask, request, jsonify
import base64
from werkzeug.utils import secure_filename
app = Flask(__name__)
# Define allowed extensions
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
def allowed_file(filename):
"""
Check if the file has one of the allowed extensions.
"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/upload_image', methods=['POST'])
def upload_image():
"""
Handle image upload and convert it to Base64 encoding.
"""
# Check if the request contains a file part
if 'file' not in request.files:
return jsonify({"error": "No file part in the request."}), 400
file = request.files['file']
# If no file is selected
if file.filename == '':
return jsonify({"error": "No file selected for uploading."}), 400
# Validate and process the file
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
try:
# Read the file as binary data
file_content = file.read()
# Encode the binary data to Base64
base64_encoded = base64.b64encode(file_content)
# Convert bytes to string
base64_string = base64_encoded.decode('utf-8')
# Return the Base64 string
return jsonify({
"filename": filename,
"base64_image": base64_string
}), 200
except Exception as e:
return jsonify({"error": f"An error occurred: {str(e)}"}), 500
else:
return jsonify({"error": "Allowed file types are png, jpg, jpeg."}), 400
if __name__ == '__main__':
app.run(debug=True)
Explanation:
Handling Multiple Files (Optional):
If you want to handle multiple image files in a single request, you can adjust the endpoint as follows:
@app.route('/upload_images', methods=['POST'])
def upload_images():
"""
Handle multiple image uploads and convert them to Base64 encoding.
"""
files = request.files.getlist('file')
if not files:
return jsonify({"error": "No files selected for uploading."}), 400
base64_images = []
for file in files:
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
try:
file_content = file.read()
base64_encoded = base64.b64encode(file_content)
base64_string = base64_encoded.decode('utf-8')
base64_images.append({
"filename": filename,
"base64_image": base64_string
})
except Exception as e:
return jsonify({"error": f"An error occurred with file {filename}: {str(e)}"}), 500
else:
return jsonify({"error": f"File {file.filename} is not an allowed image type."}), 400
return jsonify({"images": base64_images}), 200
Client-Side Example Using curl:
To test the endpoint, you can use curl to send a POST request:
curl -X POST -F "file=@path_to_image/image.png" http://localhost:5000/upload_image
Important Notes:
- Security: Always validate and sanitize user input to prevent security vulnerabilities.
- File Size Limitations: For large images, consider setting maximum allowed payload sizes.
- Content-Type Headers: Ensure that the request's
Content-Type header is set to multipart/form-data when uploading files.
Conclusion:
This Flask application provides a simple and effective way to receive image files and convert them to Base64 encoding, which can be useful for embedding images in JSON responses or data URIs.