tinify 0.1.0

A high-performance Rust client for the Tinify API, providing image compression and optimization capabilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# Tinify Examples

This directory contains comprehensive examples demonstrating all features of the `tinify` library. All examples are designed to work with the provided API key and demonstrate production-ready usage patterns.

## Quick Start

### Prerequisites

```bash
# Set your Tinify API key (optional - examples use a provided key by default)
export TINIFY_API_KEY="your-api-key-here"

# For cloud storage examples (optional - examples show expected behavior with demo credentials)
export AWS_ACCESS_KEY_ID="your-aws-access-key"
export AWS_SECRET_ACCESS_KEY="your-aws-secret-key"
export GCP_ACCESS_TOKEN="your-gcp-access-token"
```

### Running Examples

```bash
# Run individual examples
cargo run --example 01_compressing_images
cargo run --example 02_resizing_images
cargo run --example 03_converting_images
cargo run --example 04_preserving_metadata
cargo run --example 05_saving_to_s3
cargo run --example 06_saving_to_gcs
cargo run --example 07_error_handling
cargo run --example 08_compression_count
cargo run --example 09_s3_compatible_storage
cargo run --example 10_comprehensive_demo

# Run all examples
cargo run --example 10_comprehensive_demo
```

## Examples Overview

### 1. Basic Image Compression (`01_compressing_images.rs`)

Demonstrates the core functionality of image compression:
- Loading images from files
- Compressing images from memory buffers
- Compressing images from URLs
- Basic error handling

**Key Features:**
```rust
let client = Tinify::new(api_key)?;
let source = client.source_from_file("input.png").await?;
source.to_file("output.png").await?;
```

### 2. Image Resizing (`02_resizing_images.rs`)

Shows all available resizing methods and options:
- **Scale**: Maintains aspect ratio
- **Fit**: Fits within dimensions
- **Cover**: Covers entire area (may crop)
- **Thumb**: Intelligent cropping for thumbnails

**Key Features:**
```rust
let resize_options = ResizeOptions {
    method: ResizeMethod::Fit,
    width: Some(300),
    height: Some(200),
};
let result = source.resize(resize_options).await?;
```

### 3. Format Conversion (`03_converting_images.rs`)

Demonstrates format conversion capabilities:
- PNG to JPEG with background colors
- PNG to WebP for web optimization
- PNG to AVIF for next-generation formats
- Custom background colors for transparency

**Key Features:**
```rust
let convert_options = ConvertOptions {
    format: ImageFormat::Jpeg,
    background: Some("#FFFFFF".to_string()),
};
let result = source.convert(convert_options).await?;
```

### 4. Metadata Preservation (`04_preserving_metadata.rs`)

Shows how to preserve image metadata during compression:
- Copyright information
- Creation date/time
- GPS location data (JPEG only)
- Multiple metadata types

**Key Features:**
```rust
let preserve_options = PreserveOptions {
    preserve: vec![
        PreserveMetadata::Copyright,
        PreserveMetadata::Creation,
        PreserveMetadata::Location,
    ],
};
let result = source.preserve(preserve_options).await?;
```

### 5. Amazon S3 Storage (`05_saving_to_s3.rs`)

Demonstrates direct storage to Amazon S3:
- Basic S3 storage
- Public ACL configuration
- Custom headers (Cache-Control, Expires)
- Multiple AWS regions
- Different path structures

**Key Features:**
```rust
let s3_options = S3Options {
    aws_access_key_id: "your-key".to_string(),
    aws_secret_access_key: "your-secret".to_string(),
    region: "us-east-1".to_string(),
    path: "bucket/path/image.png".to_string(),
    headers: Some(custom_headers),
    acl: Some("public-read".to_string()),
};
source.store(StoreOptions::S3(s3_options)).await?;
```

### 6. Google Cloud Storage (`06_saving_to_gcs.rs`)

Shows direct storage to Google Cloud Storage:
- Basic GCS storage
- Custom metadata headers
- Different bucket structures
- Authentication patterns
- Content-Type handling

**Key Features:**
```rust
let gcs_options = GCSOptions {
    gcp_access_token: "your-token".to_string(),
    path: "bucket/path/image.png".to_string(),
    headers: Some(metadata_headers),
};
source.store(StoreOptions::GCS(gcs_options)).await?;
```

### 7. Error Handling (`07_error_handling.rs`)

Comprehensive error handling demonstration:
- Invalid API key detection
- File not found errors
- Unsupported format errors
- File size limit errors
- Network error handling
- Recovery patterns

**Key Features:**
```rust
match client.source_from_file("nonexistent.png").await {
    Ok(source) => { /* handle success */ },
    Err(TinifyError::FileNotFound { path }) => {
        println!("File not found: {:?}", path);
    },
    Err(e) => { /* handle other errors */ },
}
```

### 8. Compression Count Tracking (`08_compression_count.rs`)

Shows how to monitor API usage and quota:
- Compression count tracking
- Quota monitoring patterns
- Usage analytics
- Batch processing with limits
- Response header analysis

**Key Features:**
```rust
let mut result = source.resize(options).await?;
if let Some(count) = result.compression_count() {
    println!("Current usage: {}", count);
    monitor_quota(count);
}
```

### 9. S3-Compatible Storage (`09_s3_compatible_storage.rs`)

Demonstrates storage to S3-compatible services:
- DigitalOcean Spaces
- Backblaze B2
- Wasabi Hot Cloud Storage
- G-Core Labs
- MinIO (self-hosted)
- Service comparison and pricing

**Key Features:**
```rust
// Works with any S3-compatible service
let do_spaces_options = S3Options {
    aws_access_key_id: "spaces-key".to_string(),
    aws_secret_access_key: "spaces-secret".to_string(),
    region: "nyc3".to_string(), // DigitalOcean region
    path: "my-space/image.png".to_string(),
    // ... other options
};
```

### 10. Comprehensive Demo (`10_comprehensive_demo.rs`)

Complete demonstration of all library features:
- Builder pattern configuration
- All operation types
- Performance monitoring
- Error handling
- Usage statistics
- File cleanup

**Key Features:**
```rust
let client = Tinify::builder()
    .api_key(&api_key)
    .app_identifier("MyApp/1.0")
    .timeout(Duration::from_secs(30))
    .max_retry_attempts(3)
    .requests_per_minute(100)
    .build()?;
```

## Configuration Patterns

### Environment Variables

The examples support these environment variables:

```bash
# Required
TINIFY_API_KEY="your-tinify-api-key"

# For S3/S3-compatible services
AWS_ACCESS_KEY_ID="your-access-key"
AWS_SECRET_ACCESS_KEY="your-secret-key"
DO_SPACES_KEY="your-digitalocean-key"
DO_SPACES_SECRET="your-digitalocean-secret"
B2_APPLICATION_KEY_ID="your-b2-key-id"
B2_APPLICATION_KEY="your-b2-application-key"
WASABI_ACCESS_KEY="your-wasabi-key"
WASABI_SECRET_KEY="your-wasabi-secret"

# For Google Cloud Storage
GCP_ACCESS_TOKEN="your-gcp-access-token"
GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
```

### Builder Pattern Configuration

```rust
use tinify::{Tinify, RetryConfig, RateLimit};
use std::time::Duration;

let retry_config = RetryConfig {
    max_attempts: 5,
    base_delay: Duration::from_millis(200),
    max_delay: Duration::from_secs(30),
    backoff_factor: 2.0,
};

let rate_limit = RateLimit {
    requests_per_minute: 200,
    burst_capacity: 15,
};

let client = Tinify::builder()
    .api_key("your-api-key")
    .app_identifier("YourApp/1.0")
    .timeout(Duration::from_secs(60))
    .retry_config(retry_config)
    .rate_limit(rate_limit)
    .build()?;
```

## Error Handling Patterns

### Comprehensive Error Matching

```rust
use tinify::TinifyError;

match operation_result {
    Ok(result) => { /* handle success */ },
    Err(TinifyError::InvalidApiKey) => {
        eprintln!("Authentication failed - check your API key");
    },
    Err(TinifyError::FileNotFound { path }) => {
        eprintln!("File not found: {:?}", path);
    },
    Err(TinifyError::FileTooLarge { size, max_size }) => {
        eprintln!("File too large: {} bytes (max: {} bytes)", size, max_size);
    },
    Err(TinifyError::QuotaExceeded { limit, count }) => {
        eprintln!("Monthly quota exceeded: {} / {}", count, limit);
    },
    Err(e) => {
        eprintln!("Unexpected error: {}", e);
    }
}
```

### Recovery Patterns

```rust
// Retry pattern for transient errors
let max_retries = 3;
for attempt in 1..=max_retries {
    match client.source_from_file("image.png").await {
        Ok(source) => {
            println!("Success on attempt {}", attempt);
            break;
        },
        Err(TinifyError::NetworkError(_)) if attempt < max_retries => {
            println!("Network error, retrying... ({}/{})", attempt, max_retries);
            tokio::time::sleep(Duration::from_secs(attempt)).await;
        },
        Err(e) => {
            eprintln!("Failed after {} attempts: {}", attempt, e);
            return Err(e.into());
        }
    }
}
```

## Performance Optimization

### Batch Processing

```rust
use futures::future::try_join_all;

// Process multiple images concurrently
let files = vec!["image1.png", "image2.png", "image3.png"];
let futures = files.into_iter().map(|file| async {
    let source = client.source_from_file(file).await?;
    source.to_file(&format!("compressed_{}", file)).await
});

try_join_all(futures).await?;
```

### Memory Management

```rust
// Use streaming for large files
use tokio::fs::File;

let file = File::open("large_image.png").await?;
let source = client.source_from_stream(file, "image/png").await?;
source.to_file("compressed_large.png").await?;
```

## Cloud Storage Best Practices

### S3 Configuration

```rust
use serde_json::json;

// Optimal S3 configuration for web assets
let s3_options = S3Options {
    aws_access_key_id: env::var("AWS_ACCESS_KEY_ID")?,
    aws_secret_access_key: env::var("AWS_SECRET_ACCESS_KEY")?,
    region: "us-east-1".to_string(),
    path: "images/compressed/image.png".to_string(),
    headers: Some(json!({
        "Cache-Control": "public, max-age=31536000, immutable",
        "Content-Disposition": "inline",
    })),
    acl: Some("public-read".to_string()),
};
```

### GCS Configuration

```rust
// Optimal GCS configuration with metadata
let gcs_options = GCSOptions {
    gcp_access_token: get_access_token().await?,
    path: "images-bucket/compressed/image.png".to_string(),
    headers: Some(json!({
        "Cache-Control": "public, max-age=86400",
        "X-Goog-Meta-Source": "tinify",
        "X-Goog-Meta-Version": "1.0",
    })),
};
```

## Testing Your Setup

Run the comprehensive demo to verify everything is working:

```bash
# This will test all features and provide detailed output
TINIFY_API_KEY="XZmVxmxJxbx4PZbHyxwX74v8N0LLtvqq" cargo run --example 10_comprehensive_demo
```

Expected output includes:
- ✅ Client initialization
- ✅ Image compression with size comparison
- ✅ Resize operations with different methods
- ✅ Format conversions
- ✅ Metadata preservation
- ✅ Cloud storage demonstrations (will show expected errors with demo credentials)
- ✅ Error handling verification
- ✅ Usage statistics

## Troubleshooting

### Common Issues

1. **"Image could not be decoded"**: The test PNG data is minimal. For real testing, use actual image files.

2. **Network timeouts**: Increase timeout in client configuration:
   ```rust
   let client = Tinify::builder()
       .timeout(Duration::from_secs(60))
       .build()?;
   ```

3. **Rate limiting**: Reduce request frequency or increase rate limit:
   ```rust
   let client = Tinify::builder()
       .requests_per_minute(50)
       .build()?;
   ```

4. **Cloud storage errors**: These are expected with demo credentials. Use real credentials for actual storage.

### Getting Help

- Check the [Tinify API documentation]https://tinypng.com/developers/reference
- Review error messages for specific guidance
- Ensure API key is valid and has available quota
- Verify network connectivity to tinify.com

## Next Steps

After running the examples:

1. **Integration**: Incorporate patterns into your application
2. **Configuration**: Set up production environment variables
3. **Monitoring**: Implement compression count tracking
4. **Testing**: Create comprehensive tests for your use cases
5. **Optimization**: Fine-tune settings for your specific requirements

These examples provide a complete foundation for using tinify in production applications with all major features demonstrated and ready for customization.