Compress Image
Reduce the file size of an image while maintaining acceptable visual quality, with options for quality level and maximum file size.
/api/image/compress
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
file | File | Yes | The image file to compress. Supported formats: JPEG, PNG, WebP, BMP, TIFF. |
quality | Integer | No | JPEG quality. Range: 1-100. Default: 70 . |
max_size_kb | Integer | No | The maximum file size in kilobytes. If specified, the API will attempt to compress the image to be smaller than this size. Range: 1-10000. |
output_format | String | No | The format of the output image. Options: jpeg , png , webp . Default: Same as input format or JPEG if the original format doesn't support good compression. |
resize | Boolean | No | Whether to resize the image as part of compression if needed to meet the max_size_kb requirement. Default: false . |
max_width | Integer | No | Maximum width for resizing (only used if resize is true). Range: 1-10000. Default: 1920 . |
max_height | Integer | No | Maximum height for resizing (only used if resize is true). Range: 1-10000. Default: 1080 . |
strip_metadata | Boolean | No | Whether to remove EXIF and other metadata from the image. Default: true . |
Response
Returns the compressed image in the specified or original format.
Example Request
// example.sh
curl -X POST "https://oyyi.xyz/api/image/compress" -H "accept: application/json" \
-H "Content-Type: multipart/form-data" \
-F "file=@image.jpg" \
-F "quality=70" \
--output compressed.jpg
Example with Python
// compress.py
import requests
url = "https://oyyi.xyz/api/image/compress"
files = {
'file': open('image.jpg', 'rb')
}
data = {
'quality': 70
}
response = requests.post(url, files=files, data=data)
# Save the compressed image
with open('compressed.jpg', 'wb') as f:
f.write(response.content)
Example with JavaScript
// compress.js
// Using fetch API
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('quality', '75');
formData.append('max_size_kb', '200');
fetch('https://oyyi.xyz/api/image/compress', {
method: 'POST',
body: formData
})
.then(response => response.blob())
.then(blob => {
// Create a URL for the blob
const url = URL.createObjectURL(blob);
// Create a link to download the image
const a = document.createElement('a');
a.href = url;
a.download = 'compressed.jpg';
a.click();
// Clean up by revoking the URL
URL.revokeObjectURL(url);
})
.catch(error => console.error('Error:', error));
Compression Strategies
The API uses several strategies to reduce file size, applied in this order:
- Specialized Compression Tools: Using format-specific optimizers (jpegoptim, pngquant, gifsicle, cwebp) for maximum compression.
- Format Optimization: Converting to a more efficient format if output_format is specified.
- Metadata Removal: Stripping EXIF and other metadata if strip_metadata is true.
- Quality Reduction: Applying the specified quality level for lossy compression.
- Resizing: If resize is true and the file is still larger than max_size_kb, the image dimensions are reduced while maintaining aspect ratio.
- Iterative Compression: If max_size_kb is specified, the quality is automatically adjusted in multiple passes to achieve the target file size.
Quality Levels
High (80-100)
Minimal visible compression artifacts, good for photography and high-quality images
Medium (50-79)
Good balance between quality and file size, suitable for web images
Low (1-49)
Visible compression artifacts, smallest file size, suitable for thumbnails or previews
How It Works
The compress endpoint reduces the file size of an image using various techniques:
- Image Loading: The uploaded image is loaded into memory.
- Format Detection: The image format is detected to determine the optimal compression method.
- Specialized Compression: Format-specific external tools are used for optimal compression:
- JPEG: jpegoptim for superior JPEG compression
- PNG: pngquant for efficient lossy PNG compression
- GIF: gifsicle for GIF optimization
- WebP: cwebp (from libwebp) for WebP compression
- Format Selection: If output_format is specified, the image is prepared for conversion to that format. Otherwise, the original format is used (or JPEG for formats that don't compress well).
- Metadata Handling: If strip_metadata is true (default), EXIF and other metadata are removed from the image.
- Initial Compression: The image is compressed using the specified quality level.
- Size Check: If max_size_kb is specified, the resulting file size is checked against this limit.
- Iterative Compression: If the file is still too large:
- If resize is true, the image dimensions are reduced while maintaining aspect ratio, up to the specified max_width and max_height.
- The quality level is automatically adjusted in multiple passes to achieve the target file size.
- If the target size cannot be achieved even with minimum quality and resizing, the smallest possible version is returned.
The result is an image with a reduced file size that maintains an acceptable level of visual quality based on the specified parameters.
Format Recommendations
For the best compression results:
- WebP: Provides the best balance of quality and file size for most images. Recommended for web use if browser compatibility is not an issue.
- JPEG: Good for photographs and images with many colors. Widely supported across all platforms.
- PNG: Use only when transparency is required, as it typically results in larger file sizes than JPEG or WebP.
Error Responses
Status Code | Description |
---|---|
400 | Bad request. Missing required parameters, invalid quality value, invalid max_size_kb value, invalid output_format, invalid resize value, invalid max_width/max_height values, invalid strip_metadata value, or invalid file format. |
413 | Payload too large. The file size exceeds the maximum allowed limit. |
500 | Internal server error. Something went wrong on the server. |
Notes
- The API uses specialized external tools (jpegoptim, pngquant, gifsicle, cwebp) for optimal compression when available.
- The compression process is lossy for JPEG and WebP formats, meaning some image data is permanently discarded to reduce file size.
- PNG compression with pngquant is lossy but visually lossless, providing much better compression than traditional lossless PNG compression.
- Stripping metadata can significantly reduce file size, especially for photos from digital cameras that contain extensive EXIF data.
- When specifying max_size_kb, be realistic about the target size based on the image dimensions and content. Very low values may result in poor quality.
- If both quality and max_size_kb are specified, the quality parameter serves as the initial quality level, which may be automatically reduced to meet the size requirement.
- The maximum file size allowed for input is 50MB.
- For transparent images (PNG, WebP), converting to JPEG will replace transparency with a white background.
Use Cases
- Optimizing images for web pages to improve loading speed
- Reducing file size for email attachments
- Preparing images for upload to social media platforms with size limits
- Creating optimized image assets for mobile applications
- Batch processing large collections of images to save storage space
- Generating thumbnails or previews with small file sizes
- Meeting specific file size requirements for submissions or uploads
- Reducing bandwidth usage for image-heavy applications