Step-by-step guide to send image as Base64 to your ML backend. Discover expert tips and code examples for seamless integration!

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
// Assume you have an in your HTML
// Select the file input element
const imageInput = document.getElementById('imageInput');
// Listen for changes on the input element
imageInput.addEventListener('change', event => {
const file = event.target.files[0]; // Get the first selected file
if (file) {
// Create an instance of FileReader
const reader = new FileReader();
// Define the onload callback when the file is read completely
reader.onload = () => {
// The Base64 encoded string is available in reader.result
const base64String = reader.result.split(',')[1]; // Remove the data prefix
// Call function to send the Base64 string to the ML backend
sendImageToBackend(base64String);
};
// Read the file as a data URL (this includes the Base64 encoded string)
reader.readAsDataURL(file);
}
});
// Function to send the Base64 encoded image to the ML backend
function sendImageToBackend(base64String) {
// Example: Using fetch API to post data to backend
fetch('https://your-ml-backend/api/process-image', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
// Send as JSON with an image key
body: JSON.stringify({ image: base64String })
})
.then(response => response.json())
.then(data => {
// Process response data returned from ML backend
console.log('ML response:', data);
})
.catch(error => {
// Handle errors
console.error('Error sending image:', error);
});
}
from flask import Flask, request, jsonify
import base64
from io import BytesIO
from PIL import Image // Python Imaging Library to open images
app = Flask(**name**)
# Define an endpoint to handle image data
@app.route('/api/process-image', methods=['POST'])
def process\_image():
data = request.get\_json() // Get JSON data from the request
if 'image' not in data:
return jsonify({'error': 'No image provided'}), 400
base64\_image = data['image']
try:
// Decode the Base64 string; add missing padding if needed
image_data = base64.b64decode(base64_image)
// Create a BytesIO object from the decoded data
image_buffer = BytesIO(image_data)
// Open the image using PIL
image = Image.open(image\_buffer)
// Insert machine learning processing logic here
// For instance, pass the image to your ML model for inference
# model_output = your_ml\_model.predict(image)
// Return a dummy response for demonstration
return jsonify({'message': 'Image processed successfully', 'result': 'dummy\_output'})
except Exception as e:
// Handle errors (invalid Base64, corrupt image data, etc.)
return jsonify({'error': str(e)}), 500
if **name** == '**main**':
app.run(debug=True)
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â