Image Processing API Documentation

Documentation to help you integrate, and automate image processing with ease.

Overview

The Image Processing API enables users to resize, convert, and adjust the quality of image files, while ensuring secure access through API key authentication and preventing abuse with rate and size limits.

API Resources

To help you get started with the BestImageAPI, we provide comprehensive documentation in multiple formats:

These resources are designed to make it easy for developers to understand and utilize the capabilities of BestImageAPI.

Endpoints

1. POST /v1/img/process

Processes an uploaded image file with options for resizing, format conversion, and quality adjustment.

  • Parameters

    • Headers:
      • api-key (required): API key for authentication.
    • Query Parameters:
      • file (required): The image file to process (max size: 10 MB).
      • width (optional): The desired width of the output image. Can be specified in pixels (e.g., 400) or percentage (e.g., 50%).
      • height (optional): The desired height of the output image. Can be specified in pixels or percentage.
      • format (optional): The target format for the output image. Supported formats include webp, jpg, jpeg, png, bmp, avif, tiff, gif, heic, and heif.
      • quality (optional): Compression level or quality of the output image. Valid values are between 0 and 100 (default is 100).


curl -X POST "https://api.bestimageapi.com/v1/img/process?width=50%&format=png&quality=80" \
-H "api-key: YOUR_API_KEY" \
-H "Content-Type: multipart/form-data" \
-F "file=@image-file.jpg" \
--output new-image-file.png

<?php
$api_key = 'YOUR_API_KEY'; // Replace with your actual API key
$file_path = 'image-file.jpg'; // Path to the image file you want to upload
$url = 'https://api.bestimageapi.com/v1/img/process';

$post_fields = [
'file' => new CURLFile($file_path),
];

$query_params = [
'width' => '50%',
'format' => 'png',
'quality' => 80,
];

$full_url = $url . '?' . http_build_query($query_params);
$headers = [
'api-key: ' . $api_key,
'Content-Type: multipart/form-data',
];

$ch = curl_init($full_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For development only.  REMOVE IN PRODUCTION!
$response = curl_exec($ch);

if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
} else {
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($http_code == 200) {
// Save the image.  Get filename from Content-Disposition header if present.
$content_disposition = curl_getinfo($ch, CURLINFO_CONTENT_DISPOSITION);
if ($content_disposition) {
preg_match('/filename="([^"]+)"/', $content_disposition, $matches);
if (isset($matches[1])) {
$filename = $matches[1];
} else {
$filename = 'new-image-file.png'; // Default
}
}
else{
$filename = 'new-image-file.png'; // Default
}
file_put_contents($filename, $body);
echo "Image saved as " . $filename . "\n";
} else {
echo "HTTP Status Code: " . $http_code . "\n";
echo "Response Header: " . $header . "\n";
echo "Response Body: " . $body . "\n"; // Output the error message
}
}
curl_close($ch);
?>

import requests

url = "https://api.bestimageapi.com/v1/img/process"
api_key = "YOUR_API_KEY"  # Replace with your actual API key
image_file_path = "image-file.jpg"  # Replace with the path to your image file

params = {
"width": "50%",
"format": "png",
"quality": 80
}
headers = {
"api-key": api_key
}
files = {
"file": open(image_file_path, "rb")
}

response = requests.post(url, params=params, headers=headers, files=files)

if response.status_code == 200:
with open("new-image-file.png", "wb") as f:
f.write(response.content)
print("Image processed successfully. Saved as new-image-file.png")
else:
print(f"Error: {response.status_code} - {response.text}")

const apiKey = 'YOUR_API_KEY';
const fileInput = document.getElementById('fileInput'); // Get the file input element

fileInput.addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) {
console.error('No file selected.');
return;
}

const formData = new FormData();
formData.append('file', file);

const url = 'https://api.bestimageapi.com/v1/img/process?width=50%&format=png&quality=80';

try {
const response = await fetch(url, {
method: 'POST',
headers: {
'api-key': apiKey,
},
body: formData,
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

// Handle the response as a blob (binary data)
const blob = await response.blob();

// Create an object URL for the blob
const urlObject = URL.createObjectURL(blob);

// Create a link element to trigger the download
const a = document.createElement('a');
a.href = urlObject;
a.download = 'new-image-file.png'; // Set the desired filename
document.body.appendChild(a); // Append the link to the body
a.click(); // Trigger the download
document.body.removeChild(a); // Remove the link
URL.revokeObjectURL(urlObject); // Clean up the URL object

console.log('Image processed and downloaded successfully!');

} catch (error) {
console.error('Error processing image:', error);
}
});


Coming Soon...

  • Response

    • Success (200 OK):
      • Returns the processed image file as a downloadable attachment.
    • Error:
      • 400 Bad Request: Invalid inputs (e.g., unsupported format, missing required parameters).
      • 413 Payload Too Large: File size exceeds 10 MB limit.
      • 403 Forbidden: Invalid or missing API key.
      • 429 Too Many Requests: Rate limit exceeded.
      • 500 Internal Server Error: Unexpected server error.

2. GET /v1/health

Checks the health status of the API service.

  • Parameters

    • Headers:
      • api-key (required): API key for authentication.


curl -X GET "https://api.bestimageapi.com/v1/health" \
-H "api-key: YOUR_API_KEY"

<?php
$api_key = 'YOUR_API_KEY'; // Replace with your actual API key
$url = 'https://api.bestimageapi.com/v1/health';

$headers = [
    'api-key: ' . $api_key,
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For development only. REMOVE FOR PRODUCTION
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {

    if ($http_code == 200) {
        echo "API is healthy\n";
    } else {
        echo "HTTP Status Code: " . $http_code . "\n";
        echo "Response: " . $response . "\n"; // Output the error message.
    }
}
curl_close($ch);
?>

import requests

url = "https://api.bestimageapi.com/v1/health"
api_key = "YOUR_API_KEY" # Replace with your actual API key
headers = {
    "api-key": api_key
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
    print("API is healthy.")
else:
    print(f"Error: {response.status_code} - {response.text}")

const apiKey = 'YOUR_API_KEY';
const url = 'https://api.bestimageapi.com/v1/health';

fetch(url, {
    method: 'GET',
    headers: {
        'api-key': apiKey,
    },
})
    .then((response) => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json(); // Or response.text() if it's not JSON
    })
    .then((data) => {
        console.log('API Health Status:', data); //  log the response
    })
    .catch((error) => {
        console.error('Error checking API health:', error);
    });

Coming Soon...

  • Response

    • Success (200 OK)
    • Error:
      • 403 Forbidden: Invalid or missing API key.
      • 429 Too Many Requests: Rate limit exceeded.

Features

  • Resizing:

    • Adjusts the dimensions of the image based on provided width and/or height while maintaining aspect ratio if only one dimension is specified.
  • Format Conversion:

    • Converts images to supported formats such as PNG, JPEG, WebP, and more.
  • Quality Compression:

    • Compresses or optimizes images to a desired quality level.

Security

  • API Key Authentication:

    • All requests must include a valid API key in the api-key header.
    • Invalid or missing keys will result in a 403 Forbidden response.
  • Rate Limiting:

    • Up to 60 requests per minute.
    • Exceeding this limit will result in a 429 Too Many Requests response.

Error Handling

The API provides clear error messages and appropriate HTTP status codes:

  • 400 Bad Request

    • Invalid inputs or parameters.
  • 403 Forbidden

    • Unauthorized access due to missing or invalid API key.
  • 413 Payload Too Large

    • File size exceeds the 10 MB limit.
  • 429 Too Many Requests

    • Rate limit exceeded.
  • 500 Internal Server Error

    • Unexpected issues on the server side.

Supported Formats

The following image formats are supported:

  • Input: webp, jpg, jpeg, png, bmp, avif, tiff, gif, heif, heic.
  • Output: webp, jpg, jpeg, png, bmp, avif, tiff, gif, heif, heic.

Limitations

  • Maximum file size for uploads: 10 MB (Free trial is 1 MB).
  • Rate limit: Up to 60 requests per minute.
  • Requires at least one parameter (width, height, format, or quality) for processing requests.

Example Usage

  • Resizing an Image


curl -X POST "https://api.bestimageapi.com/v1/img/process?width=400" \
     -H "api-key: YOUR_API_KEY" \
     -F "file=@image-file.jpg" \
     --output new-image-file.jpg

<?php
$api_key = 'YOUR_API_KEY';
$file_path = 'image-file.jpg';
$url = 'https://api.bestimageapi.com/v1/img/process?width=400';

$post_fields = [
    'file' => new CURLFile($file_path),
];
$headers = [
    'api-key: ' . $api_key,
    'Content-Type: multipart/form-data',
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For development only.
$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 200) {
        $filename = 'new-image-file.jpg';
        file_put_contents($filename, $body);
        echo "Image saved as " . $filename . "\n";
    } else {
        echo "HTTP Status Code: " . $http_code . "\n";
        echo "Response: " . $response . "\n";
    }
}
curl_close($ch);
?>

import requests

url = "https://api.bestimageapi.com/v1/img/process"
api_key = "YOUR_API_KEY"  # Replace with your actual API key
image_file_path = "image-file.jpg"  # Replace with the path to your image file

params = {
    "width": 400
}
headers = {
    "api-key": api_key
}
files = {
    "file": open(image_file_path, "rb")
}

response = requests.post(url, params=params, headers=headers, files=files)

if response.status_code == 200:
    with open("new-image-file.jpg", "wb") as f:
        f.write(response.content)
    print("Image resized successfully. Saved as new-image-file.jpg")
else:
    print(f"Error: {response.status_code} - {response.text}")

const apiKey = 'YOUR_API_KEY';
const fileInput = document.getElementById('resizeFileInput');

resizeFileInput.addEventListener('change', async (event) => {
    const file = event.target.files[0];
      if (!file) {
        console.error('No file selected.');
        return;
    }
    const formData = new FormData();
    formData.append('file', file);
    const url = 'https://api.bestimageapi.com/v1/img/process?width=400';
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: { 'api-key': apiKey },
            body: formData,
        });
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const blob = await response.blob();
        const urlObject = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = urlObject;
        a.download = 'resized-image.jpg';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(urlObject);
        console.log('Image resized and downloaded!');
    } catch (error) {
        console.error('Error resizing image:', error);
    }
});

Coming Soon...
  • Converting an Image Format


curl -X POST "https://api.bestimageapi.com/v1/img/process?format=webp" \
-H "api-key: YOUR_API_KEY" \
-F "file=@image-file.jpg" \
--output new-image-file.webp

<?php
$api_key = 'YOUR_API_KEY';
$file_path = 'image-file.jpg';
$url = 'https://api.bestimageapi.com/v1/img/process?format=webp';
$post_fields = [
    'file' => new CURLFile($file_path),
];
$headers = [
    'api-key: ' . $api_key,
    'Content-Type: multipart/form-data',
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For development only.
$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 200) {
        $filename = 'new-image-file.webp';
        file_put_contents($filename, $body);
        echo "Image saved as " . $filename . "\n";
    } else {
        echo "HTTP Status Code: " . $http_code . "\n";
        echo "Response: " . $response . "\n";
    }
}
curl_close($ch);
?>

import requests

url = "https://api.bestimageapi.com/v1/img/process"
api_key = "YOUR_API_KEY"  # Replace with your actual API key
image_file_path = "image-file.jpg" # Replace with your image file

params = {
    "format": "webp"
}
headers = {
    "api-key": api_key
}
files = {
    "file": open(image_file_path, "rb")
}

response = requests.post(url, params=params, headers=headers, files=files)

if response.status_code == 200:
    with open("new-image-file.webp", "wb") as f:
        f.write(response.content)
    print("Image converted successfully. Saved as new-image-file.webp")
else:
    print(f"Error: {response.status_code} - {response.text}")

const apiKey = 'YOUR_API_KEY';
const fileInput = document.getElementById('convertFileInput');

convertFileInput.addEventListener('change', async (event) => {
    const file = event.target.files[0];
      if (!file) {
        console.error('No file selected.');
        return;
    }
    const formData = new FormData();
    formData.append('file', file);
    const url = 'https://api.bestimageapi.com/v1/img/process?format=webp';
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: { 'api-key': apiKey },
            body: formData,
        });
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const blob = await response.blob();
        const urlObject = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = urlObject;
        a.download = 'converted-image.webp';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(urlObject);
        console.log('Image converted and downloaded!');
    } catch (error) {
        console.error('Error converting image:', error);
    }
});

Coming Soon...

  • Adjusting Image Quality


curl -X POST "https://api.bestimageapi.com/v1/img/process?quality=80" \
-H "api-key: YOUR_API_KEY" \
-F "file=@image-file.jpg" \
--output new-image-file.jpg

<?php
$api_key = 'YOUR_API_KEY';
$file_path = 'image-file.jpg';
$url = 'https://api.bestimageapi.com/v1/img/process?quality=80';
$post_fields = [
    'file' => new CURLFile($file_path),
];
$headers = [
    'api-key: ' . $api_key,
    'Content-Type: multipart/form-data',
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For development only.
$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 200) {
       $filename = 'new-image-file.jpg';
        file_put_contents($filename, $body);
        echo "Image saved as " . $filename . "\n";
    } else {
        echo "HTTP Status Code: " . $http_code . "\n";
        echo "Response: " . $response . "\n";
    }
}
curl_close($ch);
?>

import requests

url = "https://api.bestimageapi.com/v1/img/process"
api_key = "YOUR_API_KEY"  # Replace with your actual API key
image_file_path = "image-file.jpg"  # Replace with your image file

params = {
    "quality": 80
}
headers = {
    "api-key": api_key
}
files = {
    "file": open(image_file_path, "rb")
}

response = requests.post(url, params=params, headers=headers, files=files)

if response.status_code == 200:
    with open("new-image-file.jpg", "wb") as f:
        f.write(response.content) # Saves with original name
    print("Image quality adjusted successfully. Saved as new-image-file.jpg")
else:
    print(f"Error: {response.status_code} - {response.text}")

const apiKey = 'YOUR_API_KEY';
const fileInput = document.getElementById('qualityFileInput');
qualityFileInput.addEventListener('change', async (event) => {
    const file = event.target.files[0];
      if (!file) {
        console.error('No file selected.');
        return;
    }
    const formData = new FormData();
    formData.append('file', file);
    const url = 'https://api.bestimageapi.com/v1/img/process?quality=80';
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: { 'api-key': apiKey },
            body: formData,
        });
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const blob = await response.blob();
        const urlObject = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = urlObject;
        a.download = 'quality-adjusted-image.jpg';  // Or .webp, .png, etc.
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(urlObject);
        console.log('Image quality adjusted and downloaded!');
    } catch (error) {
        console.error('Error adjusting image quality:', error);
    }
});

Coming Soon...
  • Combining Everything in a Single Request


curl -X POST "https://api.bestimageapi.com/v1/img/process?quality=80&format=webp&width=400" \
-H "api-key: YOUR_API_KEY" \
-F "file=@image-file.jpg" \
--output new-image-file.webp

<?php
$api_key = 'YOUR_API_KEY';
$file_path = 'image-file.jpg';
$url = 'https://api.bestimageapi.com/v1/img/process?quality=80&format=webp&width=400';
$post_fields = [
    'file' => new CURLFile($file_path),
];
$headers = [
    'api-key: ' . $api_key,
    'Content-Type: multipart/form-data',
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For development only.
$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($http_code == 200) {
        $filename = 'new-image-file.webp';
        file_put_contents($filename, $body);
        echo "Image saved as " . $filename . "\n";
    } else {
        echo "HTTP Status Code: " . $http_code . "\n";
        echo "Response: " . $response . "\n";
    }
}
curl_close($ch);
?>

import requests

url = "https://api.bestimageapi.com/v1/img/process"
api_key = "YOUR_API_KEY"  # Replace with your actual API key
image_file_path = "image-file.jpg" # Replace with your image file

params = {
    "quality": 80,
    "format": "webp",
    "width": 400
}
headers = {
    "api-key": api_key
}
files = {
    "file": open(image_file_path, "rb")
}

response = requests.post(url, params=params, headers=headers, files=files)

if response.status_code == 200:
    with open("new-image-file.webp", "wb") as f:
        f.write(response.content)
    print("Image processed successfully with all options. Saved as new-image-file.webp")
else:
    print(f"Error: {response.status_code} - {response.text}")

const apiKey = 'YOUR_API_KEY';
const fileInput = document.getElementById('allOptionsFileInput');

allOptionsFileInput.addEventListener('change', async (event) => {
    const file = event.target.files[0];
    if (!file) {
        console.error('No file selected.');
        return;
    }
    const formData = new FormData();
    formData.append('file', file);
    const url = 'https://api.bestimageapi.com/v1/img/process?quality=80&format=webp&width=400';
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: { 'api-key': apiKey },
            body: formData,
        });
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const blob = await response.blob();
        const urlObject = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = urlObject;
        a.download = 'processed-image.webp';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(urlObject);
        console.log('Image processed with all options and downloaded!');
    } catch (error) {
        console.error('Error processing image with all options:', error);
    }
});

Coming Soon...

API Resources

To help you get started with the BestImageAPI, we provide comprehensive documentation in multiple formats:

These resources are designed to make it easy for developers to understand and utilize the capabilities of BestImageAPI.

For issues or questions, please contact the BestImageAPI support team at support@bestimageapi.com.