foodshare-image
Image processing utilities for format detection, metadata extraction, and smart resizing.
Features
- Format Detection - Identify image format from magic bytes (not file extension)
- Metadata Extraction - Get dimensions without decoding entire image
- Smart Width Calculation - Optimal resize dimensions based on file size
- Image Resizing - Resize images with quality preservation (optional feature)
Installation
Add to your Cargo.toml:
[]
= "1.3"
# With image processing (adds ~2MB to binary)
= { = "1.3", = ["processing"] }
Feature Flags
| Feature | Default | Description |
|---|---|---|
processing |
No | Enable image resize/optimization |
Usage
Format Detection
Detect image format from magic bytes (first few bytes of file):
use ;
let jpeg_bytes = &;
let format = detect_format;
assert_eq!;
let png_bytes = &;
let format = detect_format;
assert_eq!;
Supported Formats
| Format | Magic Bytes | Extension |
|---|---|---|
| JPEG | FF D8 FF |
.jpg, .jpeg |
| PNG | 89 50 4E 47 |
.png |
| GIF | 47 49 46 38 |
.gif |
| WebP | 52 49 46 46...57 45 42 50 |
.webp |
| AVIF | ...66 74 79 70 61 76 69 66 |
.avif |
| HEIC | ...66 74 79 70 68 65 69 63 |
.heic |
| BMP | 42 4D |
.bmp |
| TIFF | 49 49 2A 00 or 4D 4D 00 2A |
.tiff |
| ICO | 00 00 01 00 |
.ico |
| SVG | 3C 73 76 67 or 3C 3F 78 6D 6C |
.svg |
Metadata Extraction
Get image dimensions without fully decoding:
use extract_metadata;
let metadata = extract_metadata?;
println!;
println!;
Smart Width Calculation
Calculate optimal resize width based on file size tiers:
use ;
let file_size = 2_500_000; // 2.5 MB
let original_width = 4000;
let target = calculate_target_width;
// Returns optimal width for the size tier
// Size tiers:
// - Tiny: < 100 KB -> no resize
// - Small: 100 KB - 500 KB -> max 1200px
// - Medium: 500 KB - 2 MB -> max 1600px
// - Large: 2 MB - 5 MB -> max 2000px
// - XLarge: > 5 MB -> max 2400px
Image Resizing (requires processing feature)
use ;
let options = ResizeOptions ;
let resized = resize_image?;
CLI Tool
The fs-image binary provides command-line access:
# Detect format
# Get metadata
# Resize image
Use Cases
Pre-upload Optimization
use ;
Format Validation
use ;
Performance
- Format detection: ~10ns (just reads first few bytes)
- Metadata extraction: ~1µs (reads headers only)
- Full resize: depends on image size
License
MIT License - see LICENSE for details.