exiftool-rs-wrapper 0.1.2

一个高性能、类型安全的 ExifTool Rust 封装库,支持异步 API
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# ExifTool Rust Wrapper

[![crates.io](https://img.shields.io/crates/v/exiftool-rs-wrapper.svg)](https://crates.io/crates/exiftool-rs-wrapper)
[![docs.rs](https://docs.rs/exiftool-rs-wrapper/badge.svg)](https://docs.rs/exiftool-rs-wrapper)
[![CI](https://github.com/openappsys/exiftool-rs-wrapper/workflows/CI/badge.svg)](https://github.com/openappsys/exiftool-rs-wrapper/actions)
[![License: MIT OR Apache-2.0](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue.svg)](LICENSE)
[![Rust Version](https://img.shields.io/badge/rust-1.94%2B-orange.svg)](https://www.rust-lang.org)

[中文]README.md | **English**

> A high-performance, type-safe Rust wrapper for ExifTool with 100% feature coverage

## Introduction

`exiftool-rs-wrapper` is a modern Rust library for reading, writing, and managing metadata of multimedia files including images, videos, and audio. This library wraps the powerful [ExifTool](https://exiftool.org/) command-line tool with an idiomatic Rust API.

### Core Features

- **100% Feature Coverage**: Complete support for all ExifTool read, write, and advanced features
- **High Performance**: Uses `-stay_open` mode to keep the process running, avoiding startup overhead
- **Type Safety**: Complete tag type system with strongly-typed APIs
- **Async Support**: Tokio-based async API (optional feature)
- **Connection Pool**: Built-in connection pool for high-concurrency scenarios
- **Builder Pattern**: Fluent API design with method chaining

## Feature Highlights

### Metadata Reading

- Read EXIF, IPTC, XMP, and other standard metadata
- Support for 200+ file formats (JPEG, PNG, RAW, MP4, PDF, etc.)
- Selective reading of specific tags
- Batch queries for multiple files
- Raw values and formatted values
- Grouped output by category

### Metadata Writing

- Write any tag supported by ExifTool
- Delete specific tags
- Batch write operations
- Conditional writes (only modify when conditions are met)
- DateTime offset adjustments
- Copy tags from other files
- Backup and overwrite modes supported

### Advanced Features

- **File Operations**: Rename and organize files based on metadata
- **Geolocation**: GPS coordinate read/write, reverse geocoding
- **Binary Data**: Thumbnail and preview extraction
- **Format Conversion**: Multiple output formats (JSON, XML, CSV, etc.)
- **Checksums**: Calculate file checksums (MD5, SHA256, etc.)
- **Streaming**: Large file processing with progress tracking
- **Error Recovery**: Configurable retry strategies

### Performance Optimizations

- Connection pooling for concurrent access
- LRU cache to reduce repeated queries
- Batch operation optimization
- Streaming for large files

## Installation

### 1. Install ExifTool

Before using this library, you need to install ExifTool on your system:

**macOS:**
```bash
brew install exiftool
```

**Ubuntu/Debian:**
```bash
sudo apt-get install libimage-exiftool-perl
```

**Windows:**
Download and install from [Windows version](https://exiftool.org/)

**Verify Installation:**
```bash
exiftool -ver
```

### 2. Add Dependency

Add to your `Cargo.toml`:

```toml
[dependencies]
exiftool-rs-wrapper = "0.1.0"

# Enable async support (optional)
exiftool-rs-wrapper = { version = "0.1.0", features = ["async"] }
```

## Quick Start

### Basic Example

```rust
use exiftool_rs_wrapper::ExifTool;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create ExifTool instance (-stay_open mode)
    let exiftool = ExifTool::new()?;
    
    // Read file metadata
    let metadata = exiftool.query("photo.jpg").execute()?;
    
    // Access specific tags
    if let Some(make) = metadata.get("Make") {
        println!("Camera Make: {}", make);
    }
    
    if let Some(model) = metadata.get("Model") {
        println!("Camera Model: {}", model);
    }
    
    // Get image dimensions
    let width: i64 = exiftool.read_tag("photo.jpg", "ImageWidth")?;
    let height: i64 = exiftool.read_tag("photo.jpg", "ImageHeight")?;
    println!("Image Size: {} x {}", width, height);
    
    Ok(())
}
```

### Writing Metadata

```rust
use exiftool_rs_wrapper::ExifTool;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let exiftool = ExifTool::new()?;
    
    // Basic write (creates backup)
    exiftool.write("photo.jpg")
        .tag("Copyright", "© 2026 My Company")
        .tag("Artist", "John Doe")
        .execute()?;
    
    // Overwrite original file (no backup)
    exiftool.write("photo.jpg")
        .tag("Comment", "Processed with Rust")
        .overwrite_original(true)
        .execute()?;
    
    // Delete tags
    exiftool.write("photo.jpg")
        .delete("GPSPosition")
        .overwrite_original(true)
        .execute()?;
    
    Ok(())
}
```

### Batch Processing

```rust
use exiftool_rs_wrapper::ExifTool;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let exiftool = ExifTool::new()?;
    
    let paths = vec!["photo1.jpg", "photo2.jpg", "photo3.jpg"];
    
    // Batch query
    let results = exiftool.query_batch(&paths)
        .tag("FileName")
        .tag("ImageSize")
        .tag("DateTimeOriginal")
        .execute()?;
    
    for (path, metadata) in results {
        println!("{}: {:?}", path.display(), metadata.get("FileName"));
    }
    
    Ok(())
}
```

## Detailed API Usage Examples

### Using Tag Constants (Type Safety)

```rust
use exiftool_rs_wrapper::{ExifTool, TagId};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let exiftool = ExifTool::new()?;
    
    // Use TagId constants instead of strings
    let make: String = exiftool.read_tag("photo.jpg", TagId::MAKE)?;
    let model: String = exiftool.read_tag("photo.jpg", TagId::MODEL)?;
    let iso: i64 = exiftool.read_tag("photo.jpg", TagId::ISO)?;
    
    println!("{} {} @ ISO {}", make, model, iso);
    
    // Write using TagId
    exiftool.write("photo.jpg")
        .tag_id(TagId::COPYRIGHT, "© 2026")
        .tag_id(TagId::ARTIST, "Photographer")
        .overwrite_original(true)
        .execute()?;
    
    Ok(())
}
```

### Advanced Query Options

```rust
use exiftool_rs_wrapper::ExifTool;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let exiftool = ExifTool::new()?;
    
    // Advanced query configuration
    let metadata = exiftool.query("photo.jpg")
        .include_unknown(true)          // Include unknown tags
        .include_duplicates(true)       // Include duplicate tags
        .raw_values(true)               // Return raw values
        .group_by_category(true)        // Group by category
        .tag("Make")                     // Query only specific tags
        .tag("Model")
        .tag("DateTimeOriginal")
        .exclude("MakerNotes")           // Exclude specific tags
        .execute()?;
    
    // Output as JSON
    let json = exiftool.query("photo.jpg")
        .execute_json()?;
    println!("{}", serde_json::to_string_pretty(&json)?);
    
    // Deserialize to custom type
    #[derive(serde::Deserialize)]
    struct PhotoInfo {
        #[serde(rename = "FileName")]
        file_name: String,
        #[serde(rename = "ImageWidth")]
        width: i64,
        #[serde(rename = "ImageHeight")]
        height: i64,
    }
    
    let info: PhotoInfo = exiftool.query("photo.jpg")
        .execute_as()?;
    
    Ok(())
}
```

### Async API

```rust
use exiftool_rs_wrapper::async_ext::AsyncExifTool;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create async ExifTool instance
    let exiftool = AsyncExifTool::new()?;
    
    // Async query
    let metadata = exiftool.query("photo.jpg").await?;
    println!("Camera: {:?}", metadata.get("Make"));
    
    // Async batch query
    let paths = vec!["photo1.jpg", "photo2.jpg", "photo3.jpg"];
    let results = exiftool.query_batch(&paths).await?;
    
    for (path, metadata) in results {
        println!("{}: {:?}", path.display(), metadata.get("FileName"));
    }
    
    // Async write
    exiftool.write_tag("photo.jpg", "Copyright", "© 2026").await?;
    
    // Async delete
    exiftool.delete_tag("photo.jpg", "GPSPosition").await?;
    
    Ok(())
}
```

### Connection Pool (High Concurrency)

```rust
use exiftool_rs_wrapper::pool::ExifToolPool;
use std::thread;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create connection pool with 4 connections
    let pool = ExifToolPool::new(4)?;
    let pool_clone = pool.clone();
    
    // Use pool in multiple threads
    let handles: Vec<_> = (0..8).map(|i| {
        let pool = pool_clone.clone();
        thread::spawn(move || {
            // Acquire connection from pool
            let conn = pool.acquire()?;
            let exiftool = conn.get().unwrap();
            
            let metadata = exiftool.query(format!("photo{}.jpg", i))
                .execute()?;
            
            println!("Thread {}: Processing complete", i);
            Ok::<(), exiftool_rs_wrapper::Error>(())
        })
    }).collect();
    
    for handle in handles {
        handle.join().unwrap()?;
    }
    
    Ok(())
}
```

### File Organization and Renaming

```rust
use exiftool_rs_wrapper::{
    ExifTool, 
    file_ops::{FileOperations, RenamePattern}
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let exiftool = ExifTool::new()?;
    
    // Rename based on DateTime
    exiftool.rename_by_pattern(
        "photo.jpg",
        RenamePattern::datetime("%Y%m%d_%H%M%S"),
    )?;
    
    // Rename based on camera model
    exiftool.rename_by_pattern(
        "photo.jpg",
        RenamePattern::tag_with_suffix(
            exiftool_rs_wrapper::TagId::MODEL,
            "_IMG"
        ),
    )?;
    
    // Organize files into directory structure
    use exiftool_rs_wrapper::file_ops::OrganizeOptions;
    
    let options = OrganizeOptions::new("/output/directory")
        .subdir(RenamePattern::datetime("%Y/%m"))  // Create subdirs by year/month
        .filename(RenamePattern::datetime("%Y%m%d_%H%M%S"))
        .extension("jpg");
    
    exiftool.organize_files(&["photo1.jpg", "photo2.jpg"], &options)?;
    
    Ok(())
}
```

### Geolocation Processing

```rust
use exiftool_rs_wrapper::{ExifTool, geo::GeoOperations};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let exiftool = ExifTool::new()?;
    
    // Read GPS coordinates
    if let Some(coord) = exiftool.get_gps_coordinates("photo.jpg")? {
        println!("Latitude: {}", coord.latitude);
        println!("Longitude: {}", coord.longitude);
        println!("Altitude: {:?}", coord.altitude);
    }
    
    // Write GPS coordinates
    use exiftool_rs_wrapper::geo::GpsCoordinate;
    
    let coord = GpsCoordinate::new(39.9042, 116.4074)
        .altitude(43.5);
    
    exiftool.set_gps_coordinates("photo.jpg", &coord)?;
    
    // Reverse geocoding (requires internet connection)
    if let Some(location) = exiftool.reverse_geocode(&coord)? {
        println!("City: {}", location.city);
        println!("Country: {}", location.country);
    }
    
    Ok(())
}
```

### Error Handling and Retries

```rust
use exiftool_rs_wrapper::{
    ExifTool, 
    retry::{RetryPolicy, with_retry_sync}
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let exiftool = ExifTool::new()?;
    
    // Configure retry policy
    let policy = RetryPolicy::new()
        .max_attempts(3)
        .initial_delay(std::time::Duration::from_millis(100))
        .exponential_backoff(true);
    
    // Execute operation with retry
    let metadata = with_retry_sync(&policy, || {
        exiftool.query("photo.jpg").execute()
    })?;
    
    println!("Successfully read metadata: {:?}", metadata.get("FileName"));
    
    Ok(())
}
```

### Streaming and Progress Tracking

```rust
use exiftool_rs_wrapper::{
    ExifTool, 
    stream::{StreamingOperations, StreamOptions}
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let exiftool = ExifTool::new()?;
    
    // Define progress callback
    let on_progress = |processed: usize, total: usize, current: &str| {
        let percent = (processed as f64 / total as f64) * 100.0;
        println!("Progress: {:.1}% ({}/{}): {}", percent, processed, total, current);
    };
    
    let options = StreamOptions::new()
        .chunk_size(1024 * 1024)  // 1MB chunks
        .progress_callback(on_progress);
    
    // Stream process large file
    let metadata = exiftool.stream_query("large_video.mp4", &options)?;
    
    Ok(())
}
```

## Performance Benchmarks

Performance test results on typical hardware (for reference only):

| Operation | Single Thread | Pool(4) | Async |
|-----------|---------------|---------|-------|
| Read single JPEG | ~5ms | - | ~5ms |
| Batch read 100 files | 450ms | 120ms | 110ms |
| Write single tag | ~15ms | - | ~15ms |
| Batch write 100 files | 1.5s | 450ms | 420ms |

### Optimization Tips

1. **Use Connection Pool**: Connection pooling significantly improves performance in high-concurrency scenarios
2. **Batch Operations**: Use batch APIs instead of looping single files
3. **Selective Queries**: Only query needed tags, avoid reading full metadata
4. **Enable Caching**: Use built-in LRU cache for repeated queries

## Command Line Tool

This project also provides a command-line tool:

```bash
# Install CLI tool
cargo install exiftool-rs-wrapper

# Read file metadata
exiftool-rs-wrapper read photo.jpg

# Write tags
exiftool-rs-wrapper write photo.jpg Copyright "© 2026"

# Delete tags
exiftool-rs-wrapper delete photo.jpg GPSPosition

# Batch processing
exiftool-rs-wrapper batch --input-dir ./photos --output-dir ./organized

# View version
exiftool-rs-wrapper version

# List supported tags
exiftool-rs-wrapper list-tags
```

## Contributing

We welcome all forms of contributions! Please follow these steps:

### Submitting Issues

- When reporting bugs, please provide detailed reproduction steps and environment information
- When requesting features, describe the use case and expected behavior
- Search for existing issues before submitting

### Submitting Pull Requests

1. Fork this repository
2. Create feature branch: `git checkout -b feature/amazing-feature`
3. Commit changes: `git commit -m 'Add amazing feature'`
4. Push branch: `git push origin feature/amazing-feature`
5. Submit Pull Request

### Development Environment

```bash
# Clone repository
git clone https://github.com/openappsys/exiftool-rs-wrapper.git
cd exiftool-rs-wrapper

# Build project
cargo build --release

# Run tests
cargo test
cargo test --lib

# Code check
cargo clippy --all-targets -- -D warnings
cargo fmt --check
```

### Code Standards

- Follow Rust API Guidelines
- Ensure passing `cargo clippy` and `cargo fmt` checks
- Add tests for new features
- Update relevant documentation

## License

This project is dual-licensed under MIT OR Apache-2.0. You may choose either license.

- MIT License: See [LICENSE]LICENSE file
- Apache-2.0 License: See [LICENSE-APACHE]LICENSE-APACHE file (if available)

## Acknowledgments

- [ExifTool]https://exiftool.org/ by Phil Harvey - Powerful metadata processing tool
- Rust Community - Excellent language and ecosystem

## Related Links

- [Documentation]https://docs.rs/exiftool-rs-wrapper
- [Crates.io]https://crates.io/crates/exiftool-rs-wrapper
- [GitHub Repository]https://github.com/openappsys/exiftool-rs-wrapper
- [Issue Tracker]https://github.com/openappsys/exiftool-rs-wrapper/issues

---

**Note**: This library requires ExifTool to be installed on the system. ExifTool is independent software developed by Phil Harvey with its own license.