API Documentation
Image Optimization API
Overview
The Image Optimization API allows you to optimize images by compressing them to reduce file size. This API supports various image formats, and clients can upload an image for optimization.
Endpoint
POST /optimize-image
Request
- Method :
POST
- URL :
https://api.femto.cypherx.in/optimize-image
- Headers
Authorization: Bearer YOUR_API_KEY
Content-Type: multipart/form-data
- Body
level: "ultra" | "default"
- Default :
"default"
- Description : The level of optimization to be performed on the image. The default level is
"default"
. The"ultra"
level performs more aggressive optimization on the image, but it may take more time to process. - Example :
level: "ultra"
- Default :
Request Body
- Form Data
- Key :
image
- Value : Binary Image Data
- Key :
The maximum allowed image size is 75 MB. And the supported image formats are: jpg, jpeg, png, heif, avif, webp, tiff, gif, svg, RAW files (cr2, nef, arw, dng).
Response
- Status Code :
200 OK
- Headers
Content-Type: image/YOUR_IMAGE_FORMAT
Response Body
- Value : Binary Image Data
Error Response
-
Status Code :
400 Bad Request
- Headers
Content-Type: text/plain
- Body :
File type not supported
- Headers
-
Status Code :
401 Unauthorized
- Headers
Content-Type: application/json
- Body
{ "message": "Invalid API key" }
- Headers
-
Status Code :
413 Payload Too Large
- Headers
Content-Type: application/json
- Body
{ "message": "Image size is too large. Maximum allowed size is 20 MB" }
- Headers
-
Status Code :
500 Internal Server Error
- Headers
Content-Type: text/plain
- Body :
Internal Server Error
- Headers
Request Examples
Here are some sample requests in different programming languages.
cURL
The optimized image will be saved in the current directory with the name optimized_image.png
.
curl -X POST \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: multipart/form-data" \
-F "image=@test_image.png" \
-o optimized_image.png \
https://api.femto.cypherx.in/optimize-image
JavaScript
In Node.js
- Install the
axios
andform-data
packages.
npm install axios form-data
const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');
const apiUrl = 'https://api.femto.cypherx.in/optimize-image';
// Replace 'path/to/your/image.jpg' with the actual path to your image file
const imagePath = 'path/to/your/image.jpg';
// Replace 'your-api-key' with the actual API key
const apiKey = 'your-api-key';
async function optimizeImage() {
try {
// Read the image file as a buffer
const imageBuffer = fs.readFileSync(imagePath);
// Create FormData object for the file upload
const form = new FormData();
form.append('image', imageBuffer, { filename: 'image.jpg' });
// Make a POST request to the API with Authorization header
const response = await axios.post(apiUrl, form, {
headers: {
...form.getHeaders(),
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${apiKey}`,
},
responseType: 'arraybuffer',
});
// Handle the response
console.log('Response:', response.data);
} catch (error) {
console.error('Error:', error.message);
}
}
// Call the function to make the request
optimizeImage();
In Browser
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Optimization</title>
</head>
<body>
<form id="imageForm">
<input type="file" id="imageInput" accept="image/*">
<button type="button" onclick="optimizeImage()">Optimize Image</button>
</form>
<script>
async function optimizeImage() {
try {
const imageInput = document.getElementById('imageInput');
const file = imageInput.files[0];
if (!file) {
console.error('Please select an image file.');
return;
}
const form = new FormData();
form.append('image', file);
const apiKey = 'your-api-key'; // Replace with your actual API key
const apiUrl = 'https://api.femto.cypherx.in/optimize-image';
const response = await fetch(apiUrl, {
method: 'POST',
body: form,
headers: {
'Authorization': `Bearer ${apiKey}`,
},
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const optimizedImageBuffer = await response.arrayBuffer();
// Handle the optimized image buffer as needed
console.log('Optimized Image Buffer:', optimizedImageBuffer);
} catch (error) {
console.error('Error:', error.message);
}
}
</script>
</body>
</html>
Python
- Install the
requests
package.
pip install requests
import requests
from io import BytesIO
api_url = 'https://api.femto.cypherx.in/optimize-image'
# Replace 'path/to/your/image.jpg' with the actual path to your image file
image_path = 'path/to/your/image.jpg'
# Replace 'your-api-key' with the actual API key
api_key = 'your-api-key'
def optimize_image():
try:
# Read the image file as a binary stream
with open(image_path, 'rb') as image_file:
# Create a BytesIO object to simulate a file-like object
image_buffer = BytesIO(image_file.read())
# Create a FormData-like dictionary for the file upload
files = {'image': ('image.jpg', image_buffer)}
# Make a POST request to the API with Authorization header
response = requests.post(api_url, files=files, headers={'Authorization': f'Bearer {api_key}'})
# Handle the response
if response.status_code == 200:
# Assuming the response is the optimized image data
optimized_image_buffer = BytesIO(response.content)
# Handle the optimized image buffer as needed
print('Optimized Image Buffer:', optimized_image_buffer)
else:
print(f'Error: {response.status_code} - {response.text}')
except Exception as e:
print(f'Error: {str(e)}')
# Call the function to make the request
optimize_image()
Kotlin
// install the dependencies
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
}
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.Response
import java.io.File
fun optimizeImage(imagePath : String) {
try {
val apiUrl = "https://api.femto.cypherx.in/optimize-image"
val apiKey = "your-api-key"
val imageFile = File(imagePath)
val requestBody = imageFile.asRequestBody("image/YOUR_IMAGE_EXT".toMediaType())
val request = Request.Builder()
.url(apiUrl)
.addHeader("Authorization", "Bearer $apiKey")
.post(requestBody)
.build()
val client = OkHttpClient()
val response: Response = client.newCall(request).execute()
// Handle the response
println("Response: ${response.body?.string()}")
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
/*
Call the function to make the request
If you are calling this from AppcompactActivity() class then use it inside Thread
e.g.
Thread({
optimizeImage(image_path)
}).start()
*/
optimizeImage(image_path)